我有一個C函數,它在傳遞給和通過Python訪問的地址處分配內存。指針的內容確實包含C代碼中的一個結構數組,但是我無法讓ctypes正確地訪問超出第0個元素的數組。我如何獲得正確的內存偏移量以便能夠訪問非零元素?如果我嘗試使用它們的ctypes.memset函數,Python的ctypes.memset正在抱怨TypeErrors。使用Python ctypes訪問c結構數組
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
你會得到什麼錯誤?請添加整個回溯。 – yak
@yak:當人們在玩ctypes時,追溯是一種並非總是可用的特權。如果你離開了界限,規範就是Python解釋器以段落形式結束 – jsbueno