使用c_types将python数组传递给c函数

Passing python array to a c function using c_types

本文关键字:函数 数组 python types 使用      更新时间:2023-10-16

我在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)