簡體   English   中英

Python Ctypes崩潰調用C ++函數的C包裝器

[英]Python Ctypes Crashes Calling C wrapper of C++ function

我正在嘗試使用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(),一切正常很好,那個例程應該在cGaumixmod()函數中實例化的向量上運行,而不是python numpy數組。 我真的不熟悉C ++,雖然我已經多次使用C類型的C庫。 我希望擁有一些C ++,python和ctypes經驗的人可以在這里提供一些見解/指導。

謝謝!

有一個用於與C接口的新庫,您可以查看它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM