如何自定义 Python ctypes 'c_wchar_p' 和 'c_char_p' restype?

5 python ctypes python-3.x

在Python 3中

function_name.restype = c_char_p # returns bytes
Run Code Online (Sandbox Code Playgroud)

我有很多这样的功能,每一项功能我都需要做str(ret, 'utf8')。我怎样才能创建一个custom_c_char_p自动执行此操作的声明?

function_name.restype = custom_c_char_p # should return str
Run Code Online (Sandbox Code Playgroud)

C 库还输出 UTF-16,就像c_wchar_ppython 一样str,但是当我这样做时ret.encode('utf16'),我得到了UnicodeDecodeError.

我如何定制c_wchar_p以确保 Python 知道它正在转换 UTF-16 以获得正确的str返回?

Ery*_*Sun 7

您可以c_char_p使用钩子进行子类化以解码 UTF-8 字符串_check_retval_。例如:

\n\n
import ctypes\n\nclass c_utf8_p(ctypes.c_char_p):  \n    @classmethod      \n    def _check_retval_(cls, result):\n        value = result.value\n        return value.decode('utf-8')\n
Run Code Online (Sandbox Code Playgroud)\n\n

例如:

\n\n
>>> PyUnicode_AsUTF8 = ctypes.pythonapi.PyUnicode_AsUTF8\n>>> PyUnicode_AsUTF8.argtypes = [ctypes.py_object]\n>>> PyUnicode_AsUTF8.restype = c_utf8_p\n>>> PyUnicode_AsUTF8('\\u0201')\n'\xc8\x81'\n
Run Code Online (Sandbox Code Playgroud)\n\n

这不适用于 a 中的字段Structure,但由于它是一个类,因此您可以使用属性或自定义描述符来对字节进行编码和解码。

\n