c - 如何将 Python 字符串列表转换为 C 语言 wchar_t 数组?

标签 c python-3.x cython wchar-t

C 语言的源代码如下所示:

typedef wchar_t            char_t;
typedef const char_t*  const_string_t;
static const_string_t g_symbols[] = { {L"IBM"}, {L"MSFT"}, {L"YHOO"}, {L"C"} };
...
some_c_func(g_symbols)
...

some_c_func 已在较早的地方声明,例如:

int some_c_func(const_string_t* symbols)

将 g_symbols 传递给 some_c_func 函数非常重要,因此我必须在其上编写包装器,它应该看起来像这样:

ctypedef wchar_t char_t
ctypedef const char_t*  const_string_t

def some_py_func(py_list=['a', 'b', 'c']):
    g_symbols = ... # some transformation from py_list to g_symbols
    some_c_func(g_symbols)
    print('Done!')

我将不胜感激任何帮助

最佳答案

从 unicode 对象获取 wchar* 的最简单方法可能是 PyUnicode_AsWideCharString 。 Cython 不提供定义,因此您需要自己执行合适的 cdef extern :

 from libc.stddef cimport wchar_t
 from cpython.mem cimport PyMem_Free

 cdef extern from "Python.h":
     wchat_t* PyUnicode_AsWideCharString(object, Py_ssize_t*) except NULL

 def f(string):
     cdef wchar_t* c_string = PyUnicode_AsWideCharString(string, NULL)
     # use the string
     PyMem_Free(<void*>c_string) # you must free it after use

阅读文档以了解是否应该使用“size”参数。

要为wchar_t*数组分配空间,您应该使用malloccalloc。使用完该空间后,您应该释放它。您需要从 malloc

进行转换
from libc.stdlib cimport malloc, free

cdef wchar_t** strings = <wchar_t**>malloc(sizeof(wchar_t*)*length)
# do something
free(<void*>strings)

从确保内存被清理到使用 try 和finally 的常见模式:

def some_py_func(py_list):
    g_symbols = malloc(...)
    try:
        # loop through py_list getting wchar_t*
        # call your C function 
    finally:
        # loop through g_symbols calling PyMem_Free
        free(g_symbols)

您需要注意,在发生异常时,仅对有效(或NULL)指针调用PyMem_Free。请记住,malloc 中的内存可能会填充任意值,将这些值传递给 PyMem_Free 是不安全的。

关于c - 如何将 Python 字符串列表转换为 C 语言 wchar_t 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56185968/

相关文章:

python-3.x - 我的 Python 游戏敌人正在循环移动

python - 使用回调将 C 库 (GSL) 包装在 cython 代码中

c - 使用 GNU Autotools 获取 GCC 包含路径

c++ - C/C++ 如何在连续两次输入 Enter 后或在 2 个换行符后从 stdin 读取

Python3 : TypeError: list indices must be integers or slices, 不是 str

python - Pygame表面突然反转变量

python - 在 Cython 中使用 lambda 函数时出错

Python 到 cython - 提高大型数组迭代的性能

c - MPI 数组未声明

c - scanf 之后 fgets 不起作用