[英]how to call a c-function expecting a pointer to a structure with 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){
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 中調用 function 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))
它總是導致打印出任意 integer ,然后它給我一個分段錯誤。 因為長度不合適。 有人知道我在這里做錯了什么嗎?
你的字段被顛倒了。 嘗試:
class pystruc (ctypes.Structure):
_fields_=[
("arr",ptrToDouble)
("length",ctypes.c_int),
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.