使用c_types将python数组传递给c函数
Passing python array to a c function using c_types
我在C库中有一个包装器函数,它与一些python脚本交互。
int func(uint8_t *_data, int _len);
我想用python传递一个数组或列表给这个函数。怎么做呢?
创建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)
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中