Python 如何调用一个c函数,该函数需要一个指向ctypes结构的指针?

Python 如何调用一个c函数,该函数需要一个指向ctypes结构的指针?,python,pointers,structure,ctypes,Python,Pointers,Structure,Ctypes,我面临以下问题。我用C写了以下内容: #include <stdio.h> typedef struct { double *arr; int length; } str; void f(str*); int main (void){ double x[3] = {0.1,0.2,0.3}; str aa; aa.length = 3; aa.arr = x; f(&aa); return 0; } void f(str *ss){

我面临以下问题。我用C写了以下内容:

#include <stdio.h>
typedef struct {
double *arr;
int length;
} str;

void f(str*);

int main (void){
   double x[3] = {0.1,0.2,0.3};
   str aa;
   aa.length = 3;
   aa.arr = x;
   f(&aa);
   return 0;
}

void f(str *ss){
   int i;
   printf("%d\n",ss->length);
   for (i=0; i<ss->length; i++) {
      printf("%e\n",ss->arr[i]);
   }
}
应该如此。在构建共享库“pointerToStructTypes.so”之后,我从上面的C代码中调用python中的函数f,如下所示:

ptrToDouble = ctypes.POINTER(ctypes.c_double)
class pystruc (ctypes.Structure):
   _fields_=[
             ("length",ctypes.c_int),
             ("arr",ptrToDouble)
            ]
aa = pystruc()
aa.length = ctypes.c_int(4)
xx = numpy.arange(4,dtype=ctypes.c_double)
aa.arr = xx.ctypes.data_as(ptrToDouble)
myfunc = ctypes.CDLL('pointertostrucCtypes.so')
myfunc.f.argtypes = [ctypes.POINTER(pystruc)]

myfunc.f(ctypes.byref(aa))

它的结果总是打印出一个任意的整数,然后给我一个分割错误。因为长度不合适。有人知道我这里做错了什么吗?

您的字段颠倒了。尝试:

class pystruc (ctypes.Structure):
    _fields_=[
             ("arr",ptrToDouble)
             ("length",ctypes.c_int),
            ]

如果您认为这个答案是正确的,您可以将其标记为已接受。这就是计票下面的白色复选标记的意义。@Chris:如果你认为这个答案是正确的,你可以把它标记为接受。这就是计票下面的白色复选标记的目的。!
class pystruc (ctypes.Structure):
    _fields_=[
             ("arr",ptrToDouble)
             ("length",ctypes.c_int),
            ]