我遇到以下问题。在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]);
}
}
如果我将它编译成可执行文件,它可以正常工作。我收到了:
3
0.1
0.2
0.3
应该如此。从上面的C代码构建共享库'pointertostrucCtypes.so'之后,我在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))
它总是打印出一个任意整数,然后它给我一个分段错误。因为长度不合适。有人知道我在这里做错了吗?
答案 0 :(得分:3)
您的字段已颠倒过来。尝试:
class pystruc (ctypes.Structure):
_fields_=[
("arr",ptrToDouble)
("length",ctypes.c_int),
]