我有一个C函数,它希望list \ 0终止字符串作为输入:
void external_C( int length , const char ** string_list) {
// Inspect the content of string_list - but not modify it.
}
从python(带ctypes)我想根据python字符串列表调用这个函数:
def call_c( string_list ):
lib.external_C( ?? )
call_c( ["String1" , "String2" , "The last string"])
有关如何在python端建立数据结构的任何提示?请注意,我保证C函数不会改变string_list中字符串的内容。
此致
乔金姆
答案 0 :(得分:25)
def call_c(L):
arr = (ctypes.c_char_p * len(L))()
arr[:] = L
lib.external_C(len(L), arr)
答案 1 :(得分:5)
非常感谢你;这很像魅力。我还做了一个像这样的替代变体:
def call_c( L ):
arr = (ctypes.c_char_p * (len(L) + 1))()
arr[:-1] = L
arr[ len(L) ] = None
lib.external_C( arr )
然后在C函数中我遍历(char **)列表,直到找到NULL。
答案 2 :(得分:1)
我只是使用SWIG typemap
1.在demo.i
接口文件中写入自定义的typemap。
%module demo
/* tell SWIG to treat char ** as a list of strings */
%typemap(in) char ** {
// check if is a list
if(PyList_Check($input))
{
int size = PyList_Size($input);
int i = 0;
$1 = (char **)malloc((size + 1)*sizeof(char *));
for(i = 0; i < size; i++)
{
PyObject * o = PyList_GetItem($input, i);
if(PyString_Check(o))
$1[i] = PyString_AsString(o);
else
{
PyErr_SetString(PyExc_TypeError, "list must contain strings");
free($1);
return NULL;
}
}
}
else
{
PyErr_SetString(PyExc_TypeError, "not a list");
return NULL;
}
}
// clean up the char ** array
%typemap(freearg) char ** {
free((char *) $1);
}
2.生成扩展
$ swig -python demo.i // generate wrap code
$ gcc -c -fpic demo.c demo_wrap.c
$ gcc -shared demo.o demo_wrap.o -o _demo.so
3.在python中导入模块。
>>> from demo import yourfunction
答案 3 :(得分:1)
expiries = ["1M", "2M", "3M", "6M","9M", "1Y", "2Y", "3Y","4Y", "5Y", "6Y", "7Y","8Y", "9Y", "10Y", "11Y","12Y", "15Y", "20Y", "25Y", "30Y"]
expiries_bytes = []
for i in range(len(expiries)):
expiries_bytes.append(bytes(expiries[i], 'utf-8'))
expiries_array = (ctypes.c_char_p * (len(expiries_bytes)+1))()
expiries_array[:-1] = expiries_bytes