使用ctypes在Python中访问c_char_p_Array_256

1 投票
1 回答
736 浏览
提问于 2025-04-17 07:19

我有一个原生的 Python 桥接代码,它可以和一些 C 语言代码进行交互,这些 C 代码会返回一个指向数组的指针(这个数组是由结构体组成的)。这个结构体里面包含了一些字符数组(也就是字符串)。那么,我该如何将 c_char_p_Array_NNN 转换成真正的 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 *, Group **);

############# python code below: 
class Group(Structure):
    _fields_ = [("group_id", c_uint),
                ("groupname", c_char_p*256),
                ("date_created", c_char_p*32),
                ("date_modified", c_char_p*32),
                ("user_modified", c_uint),
                ("user_created", c_uint)]


def somefunc():
    myGroups = c_void_p()
    count = libnativetest.getGroups( nativePointer, byref(myGroups) )
    print "got " + str(count) + " groups!!"
    myCastedGroups = cast( myGroups, POINTER(Group*count) )
    for x in range(0,count):
        theGroup = cast( myCastedGroups[x], POINTER(Group) )
        theGroupName = theGroup.contents.groupname 
        ### Now how do I access theGroupName as a python string?
        # it is a c_char_p_Array_256 presently

1 个回答

2

这里的类型应该是 c_char*256,而不是 c_char_p*256,因为它是一个 char[256],而不是 char *[256]

string_at(theGroupName, sizeof(theGroupName))

撰写回答