返回与指针赋值之间的c\u char\p行为不一致

2024-09-19 23:36:58 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下C函数:

void AssignPointer(char **p) {
    *p = "Test1";
}

char* Return() {
    return "Test2";
}

现在考虑一下Python中的以下代码:

^{pr2}$

现在,以下工作:

c_str = ctypes.c_char_p()
lib.AssignPointer(ctypes.byref(c_str))
print(to_python_string(c_str))

但是,下面给出了AttributeError: 'bytes' object has no attribute 'value'

c_str = lib.Return()
print(to_python_string(c_str))

在第一种情况下,调试器将c_str显示为c_char_p(ADDRESS_HERE)。在第二种情况下,调试器将c_str显示为b'Test2'。在

那么这是Python/ctypes中的一个bug还是我做错了什么?在


Tags: to函数stringreturnlib情况ctypes调试器
2条回答

最后,这里有一个解决此问题的方法:

为了避免自动将c_char_p转换为bytes,请将C函数的restype设置为c_void_p

lib.Return.restype = ctypes.c_void_p

然后cast到{},然后传递给一个函数,该函数通常使用c_char_p

^{pr2}$

ctypesautomatically convertsc_char_p将值返回给bytes对象。在

Fundamental data types, when returned as foreign function call results, or, for example, by retrieving structure field members or array items, are transparently converted to native Python types. In other words, if a foreign function has a restype of c_char_p, you will always receive a Python bytes object, not a c_char_p instance.

如果需要实际的指针值,请使用ctypes.POINTER(ctypes.c_char)作为restype。在

相关问题 更多 >