我想用 cython 来包装一个 C 库。库中的一个函数就像
int hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
有两个问题:
我能用
wchar_t
in cython 做什么;如何在我的 .pyx 文件中转换字符串指针。
声明 wchar_t:
cdef extern from "stddef.h":
ctypedef void wchar_t
或从 libc 模块导入:
from libc.stddef cimport wchar_t
使用 WideCharToMultiByte 将 wchar_t 转换为 python 字符串的函数(参见CefStringToPyString):
# Declare these in .pxd file:
#
# cdef extern from "Windows.h":
# cdef int CP_UTF8
# cdef int WideCharToMultiByte(int, int, wchar_t*, int, char*, int, char*, int*)
cdef object WideCharToPyString(wchar_t *wcharstr):
cdef int charstr_bytes = WideCharToMultiByte(CP_UTF8, 0, wcharstr, -1, NULL, 0, NULL, NULL)
# Do not use malloc, otherwise you get trash data when string is empty.
cdef char* charstr = <char*>calloc(charstr_bytes, sizeof(char))
cdef int copied_bytes = WideCharToMultiByte(CP_UTF8, 0, wcharstr, -1, charstr, charstr_bytes, NULL, NULL)
if bytes == str:
pystring = "" + charstr # Python 2.7
else:
pystring = (b"" + charstr).decode("utf-8", "ignore") # Python 3
free(charstr)
return pystring
从 Python 3.2 开始,您可以使用 PyUnicode_FromWideChar(wcharstr, -1) 来执行此操作,请参阅 compostus 的评论。