考虑以下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还是我做错了什么?在
最后,这里有一个解决此问题的方法:
为了避免自动将
c_char_p
转换为bytes
,请将C函数的restype
设置为c_void_p
:然后},然后传递给一个函数,该函数通常使用
^{pr2}$cast
到{c_char_p
:ctypesautomatically converts
c_char_p
将值返回给bytes对象。在如果需要实际的指针值,请使用
ctypes.POINTER(ctypes.c_char)
作为restype
。在相关问题 更多 >
编程相关推荐