![](/img/trans.png)
[英]Python 3.x ctype c_wchar_p and c_char_p return status different from ctypes doc
[英]How to customize Python ctypes 'c_wchar_p' and 'c_char_p' restype?
在Python 3中
function_name.restype = c_char_p # returns bytes
我有很多这样的功能,每一个我需要做str(ret, 'utf8')
。 如何创建一个自动执行此操作的custom_c_char_p
,以便像这样声明?
function_name.restype = custom_c_char_p # should return str
C库还输出UTF-16作为c_wchar_p
,它通过str
到python,但当我执行ret.encode('utf16')
,我得到UnicodeDecodeError
。
如何自定义c_wchar_p
以确保Python知道它正在转换UTF-16以获得正确的str
?
您可以使用_check_retval_
钩子对c_char_p
进行子类c_char_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')
'ȁ'
这不适用于Structure
的字段,但由于它是一个类,因此您可以使用属性或自定义描述符对字节进行编码和解码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.