简体   繁体   English

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

[英]How to customize Python ctypes 'c_wchar_p' and 'c_char_p' restype?

In Python 3 在Python 3中

function_name.restype = c_char_p # returns bytes

I have many such functions and for every one I need to do str(ret, 'utf8') . 我有很多这样的功能,每一个我需要做str(ret, 'utf8') How can I create a custom_c_char_p that does this automatically to be declared like this? 如何创建一个自动执行此操作的custom_c_char_p ,以便像这样声明?

function_name.restype = custom_c_char_p # should return str

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库还输出UTF-16作为c_wchar_p ,它通过str到python,但当我执行ret.encode('utf16') ,我得到UnicodeDecodeError

How do I customize c_wchar_p to ensure Python knows it's converting UTF-16 to get a proper str back? 如何自定义c_wchar_p以确保Python知道它正在转换UTF-16以获得正确的str

You can subclass c_char_p to decode the UTF-8 string using the _check_retval_ hook. 您可以使用_check_retval_钩子对c_char_p进行子类c_char_p以解码UTF-8字符串。 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')

For example: 例如:

>>> PyUnicode_AsUTF8 = ctypes.pythonapi.PyUnicode_AsUTF8
>>> PyUnicode_AsUTF8.argtypes = [ctypes.py_object]
>>> PyUnicode_AsUTF8.restype = c_utf8_p
>>> PyUnicode_AsUTF8('\u0201')
'ȁ'

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. 这不适用于Structure的字段,但由于它是一个类,因此您可以使用属性或自定义描述符对字节进行编码和解码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM