【问题标题】:How to customize Python ctypes 'c_wchar_p' and 'c_char_p' restype?如何自定义 Python ctypes 'c_wchar_p' 和 'c_char_p' restype?
【发布时间】:2013-07-02 20:11:27
【问题描述】:

在 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

【问题讨论】:

    标签: python python-3.x ctypes


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-24
      • 2021-11-06
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      相关资源
      最近更新 更多