使用Python ctypes访问c-structs数组

时间:2011-11-29 21:48:29

标签: python c pointers ctypes

我有一个C函数,它在传递给的地址处分配内存,并通过Python访问。指针内容确实包含C代码中的结构数组,但是我无法让ctypes在第0个元素之外正确访问数组。如何获得正确的内存偏移量才能访问非零元素?如果我尝试使用他们的ctypes.memset函数,Python的ctypes.memset会抱怨TypeErrors。

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

相关:Access c_char_p_Array_256 in Python using ctypes

2 个答案:

答案 0 :(得分:3)

首先创建一个新类型,它是一个Group:

的数组
GroupArray = Group * count

然后以这种方式创建GroupArray的实例:

group_array = GroupArray.from_address(myGroups.value)

然后你的循环会像这样工作:

for x in range(0,count):
    print "~~~~~~~~~~" + group_array[x].groupname

答案 1 :(得分:3)

赫斯让我朝着正确的方向前进;解决方案是:

GroupArray = POINTER(Group * count)
group_array = GroupArray.from_address(addressof(myGroups))
for x in range(0,count):
    print "~~~~~~~~~~" + group_array.contents[x].groupname