【问题标题】:How to wrap a C function whose parameter is wchar_t pointer with cython如何用 cython 包装参数为 wchar_t 指针的 C 函数
【发布时间】:2012-10-08 09:27:06
【问题描述】:

我想用 cython 来包装一个 C 库。库中的一个函数就像

int hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);

有两个问题:

  1. 我可以用 cython 中的 wchar_t 做什么;

  2. 如何在我的 .pyx 文件中转换字符串指针。

【问题讨论】:

    标签: pointers cython


    【解决方案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 的评论。

    【讨论】:

    • 感谢 Czarek Tomczak 的回答。但是在我按照你告诉我的去做之后,出现了一个错误:名称'wchar_t'未在模块'stddef'中声明。在我检查了 stddef.pxd 之后,我认为它只是将 wchar_t 更改为 int。那么我可以在我的 .pxd 文件中做同样的事情吗?
    • @Dewey,啊,我得到了这个本地 stddef.pxd 文件,我在其中定义了 wchar_t:“ctypedef void wchar_t”。编辑答案。
    • @Dewey:我再次编辑了我的答案,添加了 CP_UTF8 和 WideCharToMultiByte 的声明。
    • JFYI:从 Python 3.2 开始,您可以使用 PyUnicode_FromWideChar(wcharstr, -1),参见 this question 中的示例。
    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多