Cythonを使用してCライブラリをラップしたいと思います。ライブラリ内の1つの関数は次のようなものです
int hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
2つの質問があります:
wchar_t
incythonで何ができますか。.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によるコメントを参照してください。