我想使用cython来包装C库。库中的一个功能就像
int hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
有两个问题:
我可以使用cython中的wchar_t
做什么;
如何转换.pyx文件中的字符串指针。
答案 0 :(得分:1)
声明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的注释。