首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python Ctypes调用C++函数的C包装器崩溃

Python Ctypes调用C++函数的C包装器崩溃
EN

Stack Overflow用户
提问于 2012-06-16 03:26:20
回答 1查看 1.2K关注 0票数 4

我正在尝试使用Python Ctypes来连接一个已发布的(闭源) C++库。我(尝试)编写了一个基本的C风格函数包装器来构造C++向量风格对象并调用C++例程。我还(尝试)编写了一个基本的python脚本来加载共享库。除了调用C++例程的那行代码之外,一切都正常,这会产生以下结果:

代码语言:javascript
复制
*** glibc detected *** python: free(): invalid next size (fast): 0x0000000001e73c00 ***

这里是文件,不幸的是我不能分享标题,但我可以写一些类似的东西,如果需要的话…

gaumixmod.cpp:

代码语言:javascript
复制
#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:

代码语言:javascript
复制
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)

我用以下命令编译这段jazz:

代码语言:javascript
复制
g++ -fPIC -c gaumixmod.cpp;
g++ -shared -o gaumixmod.so gaumixmod.o

然后运行

代码语言:javascript
复制
python gaumixmod.py

我的研究表明,这个错误类似于segFault,python试图到达其作用域之外的内存...这是我不理解的部分,因为注释掉C++行Gaumixmod::Gaumixmod(),一切都很好,该例程应该操作在cGaumixmod()函数中实例化的向量,而不是python numpy数组。我真的不熟悉C++,尽管我在C库中使用过很多次C类型。我希望有一些C++、python和ctypes经验的人可以在这里给出一些见解/指导。

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2012-08-01 04:40:02

有一个新的与C语言接口的库,你可能会怎么看它:

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11056978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档