如何自定义Python ctypes'c_wchar_p'和'c_char_p'重新类型? [英] 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
并自动将其声明为这样?
I have many such functions and for every one I need to do str(ret, 'utf8')
. How can I create a custom_c_char_p
that does this automatically to be declared like this?
function_name.restype = custom_c_char_p # should return str
C库也将UTF-16输出为 c_wchar_p
通过 str
到达python,
,但是当我执行 ret时。 encode('utf16')
,我得到 UnicodeDecodeError
。
C library also outputs UTF-16 as c_wchar_p
which comes through as str
to python,
but when I do ret.encode('utf16')
, I get UnicodeDecodeError
.
如何自定义 c_wchar_p
以确保Python知道它正在转换UTF-16以获取正确的 str
吗?
How do I customize c_wchar_p
to ensure Python knows it's converting UTF-16 to get a proper str
back?
推荐答案
您可以将 c_char_p
子类化,以使用解码UTF-8字符串。 _check_retval _
挂钩。例如:
You can subclass c_char_p
to decode the UTF-8 string using the _check_retval_
hook. For example:
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
中的一个字段,但是由于它是一个类,因此可以使用属性或自定义描述符来编码和解码字节。
This won't work for a field in a Structure
, but since it's a class, you can use a property or custom descriptor to encode and decode the bytes.
这篇关于如何自定义Python ctypes'c_wchar_p'和'c_char_p'重新类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!