简体   繁体   English

如何调用期望指向具有 ctypes 的结构的指针的 c 函数?

[英]how to call a c-function expecting a pointer to a structure with ctypes?

I face the following problem.我面临以下问题。 In C I wrote the following:在 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]);
   }
}

If I compile it to an executable it works correctly.如果我将它编译为可执行文件,它可以正常工作。 I receive:我收到:

 3
 0.1
 0.2
 0.3

as it should be.应该是这样。 After building the shared library 'pointertostrucCtypes.so' from the C-code above I call the function f in python as follows:从上面的 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))

It results always in printing out an arbitrary integer and afterwards it gives me a segmentation fault.它总是导致打印出任意 integer ,然后它给我一个分段错误。 because length does not fit.因为长度不合适。 Has somebody an idea what I do wrong here?有人知道我在这里做错了什么吗?

Your fields are reversed.你的字段被颠倒了。 Try:尝试:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM