我有以下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++代码就可以使用它。你知道吗
您的
restype
等价于double[10][3]
,但它实际返回的是double**
:我使用以下DLL代码测试(Windows):
输出:
相关问题 更多 >
编程相关推荐