本文介绍了如何将字符串的Python列表转换为wchar_t的C数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
C语言的源代码如下:
The source code in C looks like:
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声明为较早的某个地方,例如:
some_c_func is declared somewhere earlier with something like:
int some_c_func(const_string_t* symbols)
将g_symbols传递给some_c_func函数很重要,因此我必须为其编写包装器,应该看起来
It is important that g_symbols is passed to some_c_func function, so I have to write wrapper over it, that should look somehow like:
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!')
我将不胜感激
推荐答案
感谢@DavidW,但是我发现解决方案更简单:
Thanks to @DavidW, but I found, I think, simplier solution:
from cpython.mem cimport PyMem_Malloc, PyMem_Free
def some_py_func(py_list=['a', 'b', 'c']):
cdef int number = len(symbols) # get c int of elements
cdef int idx # for faster loops
# create array with dynamic memory allocation
cdef const_string_t *g_symbols = <const_string_t *> PyMem_Malloc(number * sizeof(const_string_t))
# create array with cycle
for idx, sym in enumerate(py_list):
g_symbols[idx] = PyUnicode_AsWideCharString(sym, NULL)
# call c function
some_c_func(g_symbols)
# free memory
for idx in range(number):
PyMem_Free(g_symbols[idx])
PyMem_Free(g_symbols)
print('Done!')
这篇关于如何将字符串的Python列表转换为wchar_t的C数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!