Python类型。获得2维阵列 我有这个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 }

Python类型。获得2维阵列 我有这个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 },python,c++,ctypes,Python,C++,Ctypes,现在我想使用ctypes从python调用这个函数。我试过这样的smth: 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 's

现在我想使用ctypes从python调用这个函数。我试过这样的smth:

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调用这个函数呢

< P> S。我得到了这个库,因为它是希望使用它而不重写C++代码。< /P> < P>你的ReSpe等同于double [10 ] [3 ],但是它实际上返回的是双**:

我使用以下DLL代码测试Windows:

extern "C" __declspec(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[i][j] = i*N+j;
    }
    return POINTS;
}

太可怕了!为什么手册中没有这样清晰的例子。我在这个问题上花了很多时间。谢谢
#!python3.6
import ctypes as c
dll = c.CDLL('test')
dll.points.argtypes = c.c_int,c.c_int
dll.points.restype = c.POINTER(c.POINTER(c.c_double))
arr = dll.points(10,3)
for i in range(10):
    for j in range(3):
        print(f'({i},{j}) = {arr[i][j]}')
extern "C" __declspec(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[i][j] = i*N+j;
    }
    return POINTS;
}
(0,0) = 0.0
(0,1) = 1.0
(0,2) = 2.0
(1,0) = 10.0
(1,1) = 11.0
(1,2) = 12.0
(2,0) = 20.0
(2,1) = 21.0
   :