如何定制Python ctypes';c_wchar_p';和';c#u char#u p';重新打字?
在Python 3中如何定制Python ctypes';c_wchar_p';和';c#u char#u p';重新打字?,python,python-3.x,ctypes,Python,Python 3.x,Ctypes,在Python 3中 function_name.restype = c_char_p # returns bytes 我有很多这样的函数,对于每一个函数,我都需要执行str(ret,'utf8')。我怎样才能创建一个自定义字符p,它会自动这样声明 function_name.restype = custom_c_char_p # should return str C库还将UTF-16输出为C\u wchar\u p,通过str输出到python, 但是当我执行ret.encode('ut
function_name.restype = c_char_p # returns bytes
我有很多这样的函数,对于每一个函数,我都需要执行str(ret,'utf8')
。我怎样才能创建一个自定义字符p
,它会自动这样声明
function_name.restype = custom_c_char_p # should return str
C库还将UTF-16输出为C\u wchar\u p
,通过str
输出到python,
但是当我执行ret.encode('utf16')
时,我会得到UnicodeDecodeError
如何定制
c\u wchar\u p
以确保Python知道它正在转换UTF-16以获得正确的str
返回?您可以使用\u check\u retval\ucode>钩子类c\u char\u p
来解码UTF-8字符串。例如:
import ctypes
class c_utf8_p(ctypes.c_char_p):
@classmethod
def _check_retval_(cls, result):
value = result.value
return value.decode('utf-8')
>>> PyUnicode_AsUTF8 = ctypes.pythonapi.PyUnicode_AsUTF8
>>> PyUnicode_AsUTF8.argtypes = [ctypes.py_object]
>>> PyUnicode_AsUTF8.restype = c_utf8_p
>>> PyUnicode_AsUTF8('\u0201')
'ȁ'
例如:
import ctypes
class c_utf8_p(ctypes.c_char_p):
@classmethod
def _check_retval_(cls, result):
value = result.value
return value.decode('utf-8')
>>> PyUnicode_AsUTF8 = ctypes.pythonapi.PyUnicode_AsUTF8
>>> PyUnicode_AsUTF8.argtypes = [ctypes.py_object]
>>> PyUnicode_AsUTF8.restype = c_utf8_p
>>> PyUnicode_AsUTF8('\u0201')
'ȁ'
这对结构中的字段不起作用,但由于它是一个类,因此可以使用属性或自定义描述符对字节进行编码和解码