4

Python Ctypes を使用して、公開された (クローズド ソース) C++ ライブラリに接続しようとしています。C++ ベクトル スタイル オブジェクトを構築し、C++ ルーチンを呼び出すために、基本的な C スタイルの関数ラッパーを (試して) 書きました。また、共有ライブラリをロードするための基本的な python スクリプトを (試して) 書きました。次のような C++ ルーチンを呼び出す行を除いて、すべてが機能しています。

*** glibc detected *** python: free(): invalid next size (fast): 0x0000000001e73c00 ***

ここにファイルがあります。残念ながらヘッダーを共有することはできませんが、必要に応じて似たようなものを書くことができるかもしれません...

gaumixmod.cpp:

#include "nr3.h"
#include "cholesky.h"
#include "gaumixmod.h"

extern "C" {

  void cGaumixmod(double* D, int Dm, int Dn,  double* M, int Mm, int Mn) {

    MatDoub ddata(Dm,Dn,*D); // construct Matrix (vector) type                       
    MatDoub mmeans(Mm,Mn,*M); // construct Matrix (vector) type                      

    //XXX test numpy array is coming through as C array and we can rw, checks OK
    int i;
    // for(i=0;i<Dn*Dm;++i) {                                               
    //   printf("Address %x : ",(D+i));                                     
    //   printf("was %f \t" , D[i]);                                        
    //   D[i]+=1.0;                                                         
    //   printf("now: %f \n" , D[i]);                                       
    // }                                                                    

    // check that array D was copied to matrix ddata, and we can r/w
    for(i=0;i<Dm*Dn;++i) {
      printf("iter %d Address %x : ",i,ddata[i/Dm][i%Dm]);
      printf("was %f \t" , ddata[i/Dm][i%Dm]);
      ddata[i/Dm][i%Dm]+=1.0;
      printf("now: %f \n" ,ddata[i/Dm][i%Dm]);
    }


    Gaumixmod::Gaumixmod(ddata,mmeans);

    //return data from vector to ctypes array C so we can check data returns to python
    //via numpy array, checks ok
    for(i=0;i<Dm*Dn;++i) {
      D[i] = ddata[i/Dm][i%Dm];
    }


  }

}

goumixmod.py:

import platform,ctypes
import numpy as np


# ------------------------------------------------------------------------
# define correct library from platfrom, assuming 64bit for linux machines   
# ------------------------------------------------------------------------  

if platform.system()=='Microsoft':
    raise Exception('MS not supported.')
elif platform.system()=='Darwin':
    libgaumixmod = ctypes.cdll.LoadLibrary("./gaumixmod.so")
elif platform.system()=='Linux':
    libgaumixmod = ctypes.cdll.LoadLibrary("./gaumixmod.so")
else:
    #hope for the best                                                      
    libgaumixmod = ctypes.cdll.LoadLibrary("./gaumixmod.so")

# --------------------------------------------------
# define SafeCall                                                           
#---------------------------------------------------                                  

def SafeCall(ret):
    """pass, code l8r""
    print ret
#---------------------------------------------------  
# define arg types and res types of function                                
# -----------------------------------------------------------------------             
_gaumixmod = libgaumixmod.cGaumixmod
_gaumixmod.restype = ctypes.c_int
_gaumixmod.argtypes = [np.ctypeslib.ndpointer(dtype=np.float64,flags='C_CONTIGUOUS'),
            ctypes.c_int,
            ctypes.c_int,
            np.ctypeslib.ndpointer(dtype=np.float64,flags='C_CONTIGUOUS'),
            ctypes.c_int,
            ctypes.c_int]


def gaumixmod(D,K):
    """Python binding for C++ guassian mixure model code."""

    ret = _gaumixmod(D,D.shape[0],D.shape[1],K,K.shape[0],K.shape[1])
    SafeCall(ret)
    return D,K

D = np.ones((100,100)).astype(np.float64)
K = np.ones((4,1)).astype(np.float64)

print gaumixmod(D,K)

そして、このジャズを次のようにコンパイルします。

g++ -fPIC -c gaumixmod.cpp;
g++ -shared -o gaumixmod.so gaumixmod.o

そして走る

python gaumixmod.py

私の調査によると、このエラーは segFault に似たものであり、Python がその範囲外のメモリに到達しようとしています...これは、C++ 行 Gaumixmod::Gaumixmod() をコメントアウトしているため、理解できない部分です。すべてが機能します。そのルーチンは、Python numpy 配列ではなく、cGaumixmod() 関数でインスタンス化されたベクトルで動作する必要があります。私は C ライブラリーに C の型を何度も使用してきましたが、C++ にはあまり詳しくありません。C++、python、および ctypes の経験がある人がここで洞察/ガイダンスを提供できることを願っています。

ありがとう!

4

1 に答える 1

0

C とのインターフェイス用の新しいライブラリがあります。

http://cffi.readthedocs.org/en/latest/index.html

于 2012-07-31T20:40:02.400 に答える