- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
在 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/
我正在尝试将 C 库(libmms,尽管这并不重要)与 ctypes 一起使用;我首先编写了一个小型的 C 程序,但我似乎很难让它与 ctypes 一起工作 每当我使用 test.restype =
在 Python 3 中 function_name.restype = c_char_p # returns bytes 我有很多这样的函数,我需要为每个函数执行 str(ret, 'utf8')。
奇怪的是,即使在设置了 restype 之后,python 仍会返回 long 而不是 c_void_p。 例如; # python code from ctypes import * dll = w
例如,如果能够做到这一点,那就太好了: from ctypes import CDLL mylib = CDLL('/my/path/mylib.so',header='/some/path/myli
为了获取 blob 容器详细信息,我们使用下面提到的 REST API。Vhd 是 blob 容器名称。 https://(storageAccountName).blob.core.windows.
我设法在 Web 浏览器上显示以从 mySQL 数据库中检索我的数据。但是我无法在我的 android studio v2.0 中检索我的数据。 配置.java类 public class confi
我是一名优秀的程序员,十分优秀!