【发布时间】:2017-10-30 01:59:46
【问题描述】:
我有这个 c++ 代码:
#define DLLEXPORT extern "C"
DLLEXPORT double **points(unsigned N, unsigned D)
{
double **POINTS = new double * [N];
for (unsigned i=0;i<=N-1;i++) POINTS[i] = new double [D];
for (unsigned j=0;j<=D-1;j++) POINTS[0][j] = 0;
// do some calculations, f.e:
// POINTS[i][j] = do_smth()
//
return POINTS
}
我使用这个命令编译的:
g++ -shared gpoints.cc -o gpoints.so -fPIC
现在我想使用 ctypes 从 python 调用这个函数。我是这样尝试的:
mydll = ctypes.cdll.LoadLibrary('/.gpoints.so')
func = mydll.points
mytype = c.c_double * 3 * 10
func.restype = mytype
arr = func(10, 3)
print(arr)
当我尝试运行它时,我得到:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
[1] 2794 abort python3 test.py
那么,如何从 Python 中正确调用这个函数呢?
附:我“按原样”得到了这个库,所以最好在不重写 c++ 代码的情况下使用它。
【问题讨论】: