Ser*_*tch 0 c python string interop ctypes
考虑以下 C 函数:
void AssignPointer(char **p) {
*p = "Test1";
}
char* Return() {
return "Test2";
}
Run Code Online (Sandbox Code Playgroud)
现在考虑以下 Python 代码:
import ctypes
lib = CDLL('LibraryPathHere')
lib.AssignPointer.restype = None
lib.AssignPointer.argtypes = (ctypes.POINTER(ctypes.c_char_p),)
lib.Return.restype = ctypes.c_char_p
lib.Return.argtypes = None
def to_python_string(c_str : ctypes.c_char_p) -> str:
return c_str.value.decode('ascii')
Run Code Online (Sandbox Code Playgroud)
现在进行以下工作:
c_str = ctypes.c_char_p()
lib.AssignPointer(ctypes.byref(c_str))
print(to_python_string(c_str))
Run Code Online (Sandbox Code Playgroud)
然而,以下给出AttributeError: 'bytes' object has no attribute 'value':
c_str = lib.Return()
print(to_python_string(c_str))
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,调试器显示c_str为c_char_p(ADDRESS_HERE)。在第二种情况下,调试器显示c_str为b'Test2'。
这是 Python/ctypes 中的错误还是我做错了什么?