我面临以下问题。我用 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))
它总是导致打印出任意整数,然后它给我一个段错误。因为长度不合适。有人知道我在这里做错了什么吗?
最佳答案
您的字段颠倒了。尝试:
class pystruc (ctypes.Structure):
_fields_=[
("arr",ptrToDouble)
("length",ctypes.c_int),
]
关于python - 如何调用需要指向具有 ctypes 的结构的指针的 c 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7040576/