![](/img/trans.png)
[英]Python 3.x ctype c_wchar_p and c_char_p return status different from ctypes doc
[英]How to customize Python ctypes 'c_wchar_p' and 'c_char_p' restype?
在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
?
您可以使用_check_retval_
鈎子對c_char_p
進行子類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
的字段,但由於它是一個類,因此您可以使用屬性或自定義描述符對字節進行編碼和解碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.