gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:19:28 24 4
gpt4 key购买 nike

在 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

最佳答案

您可以继承 c_char_p 以使用 _check_retval_ Hook 解码 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 中的字段,但由于它是一个类,您可以使用属性或自定义描述符来编码和解码字节。

关于python - 如何自定义 Python ctypes 'c_wchar_p' 和 'c_char_p' restype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17434977/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com