我在C库中有一个与一些python脚本交互的包装函数。
int func(uint8_t *_data, int _len);
我想将python中的数组或列表传递给此函数。 怎么做?
答案 0 :(得分:1)
创建C数组类型的最简单方法是在ctypes
中使用相应类型的乘法运算符,它会自动生成一个新类型对象。例如......
>>> import ctypes
>>> ctypes.c_ubyte * 3
<class '__main__.c_ubyte_Array_3'>
...可以用相同数量的参数构建......
>>> (ctypes.c_ubyte * 3)(0, 1, 2)
<__main__.c_ubyte_Array_3 object at 0x7fe51e0fa710>
...或者您可以使用*
运算符将其与列表的内容一起调用...
>>> (ctypes.c_ubyte * 3)(*range(3))
<__main__.c_ubyte_Array_3 object at 0x7fe51e0fa7a0>
...所以你需要像...这样的东西。
import ctypes
my_c_library = ctypes.CDLL('my_c_library.dll')
def call_my_func(input_list):
length = len(input_list)
array = (ctypes.c_ubyte * length)(*input_list)
return my_c_library.func(array, length)
my_list = [0, 1, 2]
print call_my_func(my_list)