使用Python ctypes访问C结构体数组
我有一个C语言的函数,它会在传入的地址上分配内存,然后通过Python来访问这块内存。这个指针的内容确实包含了一个结构体数组,但我在用ctypes访问这个数组时,除了第一个元素之外,其他元素都无法正确访问。我该如何获取正确的内存偏移量,以便能够访问非零元素呢?如果我尝试使用ctypes的memset函数,Python会报类型错误。
typedef struct td_Group
{
unsigned int group_id;
char groupname[256];
char date_created[32];
char date_modified[32];
unsigned int user_modified;
unsigned int user_created;
} Group;
int getGroups(LIBmanager * handler, Group ** unallocatedPointer);
############# python code below:
class Group(Structure):
_fields_ = [("group_id", c_uint),
("groupname", c_char*256),
("date_created", c_char*32),
("date_modified", c_char*32),
("user_modified", c_uint),
("user_created", c_uint)]
myGroups = c_void_p()
count = libnativetest.getGroups( nativePointer, byref(myGroups) )
casted = cast( myGroups, POINTER(Group*count) )
for x in range(0,count):
theGroup = cast( casted[x], POINTER(Group) )
# this only works for the first entry in the array:
print "~~~~~~~~~~" + theGroup.contents.groupname
2 个回答
4
D Hess 给了我很好的建议;解决方案是:
GroupArray = POINTER(Group * count)
group_array = GroupArray.from_address(addressof(myGroups))
for x in range(0,count):
print "~~~~~~~~~~" + group_array.contents[x].groupname
3
首先,创建一个新的类型,这个类型是一个包含多个组的数组:
GroupArray = Group * count
接着,按照下面的方式创建一个 GroupArray 的实例:
group_array = GroupArray.from_address(myGroups.value)
然后,你的循环可以这样运行:
for x in range(0,count):
print "~~~~~~~~~~" + group_array[x].groupname