如何用cython包装参数为wchar_t指针的C函数 [英] How to wrap a C function whose parameter is wchar_t pointer with cython

查看:109
本文介绍了如何用cython包装参数为wchar_t指针的C函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用cython包装一个C库.库中的一个功能就像

I want to use cython to wrap a C library. One function in the library is like

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

有两个问题:

  1. 如何在cython中使用wchar_t?

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

How to convert the string pointer in my .pyx file.

推荐答案

声明wchar_t:

cdef extern from "stddef.h":
    ctypedef void wchar_t

或从libc模块导入:

Or import from libc module:

from libc.stddef cimport wchar_t

使用WideCharToMultiByte将wchar_t转换为python字符串的函数(请参见 CefStringToPyString ):

A function to convert wchar_t to python string by using WideCharToMultiByte (see 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的注释.

Since Python 3.2 you can do this with the use of PyUnicode_FromWideChar(wcharstr, -1), see the comment by compostus.

这篇关于如何用cython包装参数为wchar_t指针的C函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆