Python中的动态数组和结构体中的结构体
我正在尝试在Python中使用ctypes实现这些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的文档也没有太大帮助。
1 个回答
15
我在猜测提问者想要的内容,如果有更简单的方法,请大家给我建议。不过这是我想到的解决方案:
demo.py
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))
test.c
#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;
}
makefile
这个是用Visual Studio 2010编译的。
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