Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何定制Python ctypes';c_wchar_p';和';c#u char#u p';重新打字?_Python_Python 3.x_Ctypes - Fatal编程技术网

如何定制Python ctypes';c_wchar_p';和';c#u char#u p';重新打字?

如何定制Python ctypes';c_wchar_p';和';c#u char#u p';重新打字?,python,python-3.x,ctypes,Python,Python 3.x,Ctypes,在Python 3中 function_name.restype = c_char_p # returns bytes 我有很多这样的函数,对于每一个函数,我都需要执行str(ret,'utf8')。我怎样才能创建一个自定义字符p,它会自动这样声明 function_name.restype = custom_c_char_p # should return str C库还将UTF-16输出为C\u wchar\u p,通过str输出到python, 但是当我执行ret.encode('ut

在Python 3中

function_name.restype = c_char_p # returns bytes
我有很多这样的函数,对于每一个函数,我都需要执行
str(ret,'utf8')
。我怎样才能创建一个
自定义字符p
,它会自动这样声明

function_name.restype = custom_c_char_p # should return str
C库还将UTF-16输出为
C\u wchar\u p
,通过
str
输出到python, 但是当我执行
ret.encode('utf16')
时,我会得到
UnicodeDecodeError


如何定制
c\u wchar\u p
以确保Python知道它正在转换UTF-16以获得正确的
str
返回?

您可以使用
\u check\u retval\ucode>钩子类
c\u char\u 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')
'ȁ'
例如:

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')
'ȁ'
这对
结构中的字段不起作用,但由于它是一个类,因此可以使用属性或自定义描述符对字节进行编码和解码