ctypes:如何将结构数组定义为另一个结构的字段?

时间:2017-11-17 23:11:15

标签: arrays python-3.x ctypes

我的C结构如下所示:

typedef struct _DXYZ {
    DXYZSTATE State[];
} DXYZ, *PDXYZ

基本上是一个DXYZSTATE的数组,大小未知。

当我尝试在ctypes中声明此结构时,我不知道该怎么做。

class DXYZ(Structure):
    _fields_ = [
        ('State', ???)
    ]

我用什么来表示结构的未知大小的数组?

如果它有帮助,它在C中使用的示例如下,malloc'd的大小在其他地方提供。

CurrentState = (PDXYZ) malloc(statesize);
err = update(CurrentState);

更新过程使用结构填充预先分配的空间。

1 个答案:

答案 0 :(得分:2)

这是一种方式,但它并不漂亮。 .csproj不在结构中执行变量数组,因此访问变量数据需要进行一些转换。

test.c 实现返回变量结构数据的测试函数。在这种情况下,我硬编码了一个大小为4的返回数组,但它可以是任何大小。

ctypes

<强> test.py

#include <stdlib.h>

typedef struct STATE {
    int a;
    int b;
} STATE;

typedef struct DXYZ {
    int count;
    STATE state[];
} DXYZ, *PDXYZ;

__declspec(dllexport) PDXYZ get(void)
{
    PDXYZ pDxyz = malloc(sizeof(DXYZ) + sizeof(STATE) * 4);
    pDxyz->count = 4;
    pDxyz->state[0].a = 1;
    pDxyz->state[0].b = 2;
    pDxyz->state[1].a = 3;
    pDxyz->state[1].b = 4;
    pDxyz->state[2].a = 5;
    pDxyz->state[2].b = 6;
    pDxyz->state[3].a = 7;
    pDxyz->state[3].b = 8;
    return pDxyz;
}

__declspec(dllexport) void myfree(PDXYZ pDxyz)
{
    free(pDxyz);
}

输出:

from ctypes import *
import struct

class State(Structure):
    _fields_ = [('a',c_int),
                ('b',c_int)]

class DXYZ(Structure):
    _fields_ = [('count',c_int),      # Number of state objects
                ('state',State * 0)]  # Zero-sized array

# Set the correct arguments and return type for the DLL functions.
dll = CDLL('test')
dll.get.argtypes = None
dll.get.restype = POINTER(DXYZ)
dll.myfree.argtypes = POINTER(DXYZ),
dll.myfree.restype = None

pd = dll.get()    # Get the returned pointer
d = pd.contents   # Dereference it.

print('count =',d.count)
# Cast a pointer to the zero-sized array to the correct size and dereference it.
s = cast(byref(d.state),POINTER(State * d.count)).contents

for c in s:
    print(c.a,c.b)

dll.myfree(pd)