开发者

How to declare a C struct with a pointer to array in ctypes?

I read the official ctypes tutorial and also searched SO, but I could not find a wa开发者_运维问答y to declare this kind of structure with ctypes. This structure is returned by one of the functions I write an Python interface for.

typedef struct{
    int i;
    float *b1;
    float (*w1)[];
}foo;

This is what I have so far:

class foo(Structure):
 _fields_=[("i",c_int),
  ("b1",POINTER(c_int)),
  ("w1",?????????)]

Thanks for your help!


In C, a pointer to an array stores the same memory address as a pointer to the first element in the array. Therefore:

class foo(Structure):
    _fields_=[("i",c_int),
              ("b1",POINTER(c_int)),
              ("w1",POINTER(c_float))]

You can access the elements of the array using integer indexes. For example: myfoo.w1[5].

It would be better C coding style to declare w1 as float *w1, so that you can access elements of the array using myfoo->w1[5] instead of having to dereference twice.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜