1
我想使用cython来包装C库。在图书馆的一个功能是一样如何使用cython来包装参数为wchar_t指针的C函数
int hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
有两个问题:
我能在用Cython的
wchar_t
做;如何转换我的.pyx文件中的字符串指针。
我想使用cython来包装C库。在图书馆的一个功能是一样如何使用cython来包装参数为wchar_t指针的C函数
int hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
有两个问题:
我能在用Cython的wchar_t
做;
如何转换我的.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的评论。
感谢Czarek Tomczak为您解答。但是在我按照你的意思做了什么之后,出现了一个错误:名称'wchar_t'没有在模块'stddef'中声明。在检查stddef.pxd之后,我认为它只是将wchar_t更改为int。所以我可以在.pxd文件中做同样的事情。 – Dewey
@Dewey,ahh我得到了这个本地stddef.pxd文件,我在其中定义了wchar_t:“ctypedef void wchar_t”。编辑答案。 –
@Dewey:我再次编辑我的答案以添加CP_UTF8和WideCharToMultiByte的声明。 –