python结构中的动态数组和结构

python结构中的动态数组和结构,python,ctypes,Python,Ctypes,我正在尝试使用ctypes在python中实现此C结构: struct _rows { int cols_count; char *cols[]; } struct _unit { int rows_count; struct _rows *rows; } int my_func(struct _unit *param); 问题是_rows.cols是一个动态大小的字符指针数组,_unit.rows是一个动态大小的_rows结构数组。如何在python中使用

我正在尝试使用ctypes在python中实现此C结构:

struct _rows {
    int cols_count;
    char *cols[];
}

struct _unit {
    int rows_count;
    struct _rows *rows;
}

int my_func(struct _unit *param);
问题是_rows.cols是一个动态大小的字符指针数组,_unit.rows是一个动态大小的_rows结构数组。如何在python中使用ctypes实现这一点

我能够定义一个函数,该函数将返回具有可变数量字符指针的_rows结构:

def get_row(cols):
    class Row(ctypes.Structure):
        _fields_ = [("cols_count", ctypes.c_int), 
                    ("cols", ctypes.c_char_p * cols)
                   ]

我不知道下一步该怎么办,这一切都有点模糊,ctypes文档也帮不上忙。

我正在对OP想要什么做一些假设,如果有更简单的方法,我希望得到建议,但这就是我想到的:

demo.py 测试c 输出
你在正确的轨道上。然而,如果你能提供更多关于你想要完成的事情的信息,这会有所帮助。例如,您可以添加一些伪代码来描述您需要执行的操作。非常好的答案。这正是我想要的。我现在已经学会了几个关键技巧。谢谢。这对我不起作用,我试图定义一个以char[]结尾的结构,但是使用指针(c_ubyte)会在结构中产生指针,而不是实际的字符数组。。。
import string
from ctypes import Structure,c_int,c_char_p,POINTER,cast,pointer,byref,CDLL

class Row(Structure):
    _fields_ = [('cols_count', c_int), 
                ('cols', POINTER(c_char_p))]
    def __init__(self,cols):
        self.cols_count = cols
        # Allocate an array of character pointers
        pc = (c_char_p * cols)()
        self.cols = cast(pc,POINTER(c_char_p))            

class Unit(Structure):
    _fields_ = [('rows_count', c_int),
                ('rows',POINTER(Row))]
    def __init__(self,rows,cols):
        self.rows_count = rows
        # Allocate an array of Row structures.
        # This does NOT call __init__.
        pr = (Row * rows)()
        # Call init manually with the column size.
        for r in pr:
            r.__init__(cols)
        self.rows = cast(pr,POINTER(Row))

unit = Unit(2,3)

# Stuff some strings ('aaaaa','bbbbb',etc.)
for i in xrange(unit.rows_count):
    for j in xrange(unit.rows[i].cols_count):
        unit.rows[i].cols[j] = string.ascii_lowercase[i*5+j]*5

dll = CDLL('test.dll')
dll.my_func(byref(unit))
#include <stdio.h>

struct _rows {
    int cols_count;
    char **cols;
};

struct _unit {
    int rows_count;
    struct _rows *rows;
};

__declspec(dllexport) int my_func(struct _unit *param)
{
    int i,j;
    for(i=0;i<param->rows_count;i++)
        for(j=0;j<param->rows[i].cols_count;j++)
            printf("%d,%d = %s\n",i,j,param->rows[i].cols[j]);
    return 0;
}
test.dll: test.c
    cl /W4 /LD test.c
0,0 = aaaaa
0,1 = bbbbb
0,2 = ccccc
1,0 = fffff
1,1 = ggggg
1,2 = hhhhh