Reputation: 1337
I have a wrapper function in C library that interacts with the some python scripts.
int func(uint8_t *_data, int _len);
I want to pass a array or list in python to this function. How to do it ?
Upvotes: 1
Views: 206
Reputation: 41950
The simplest way to create a C array type is to use the multiplication operator on the appropriate type in ctypes
, which automatically generates a new type object. For example...
>>> import ctypes
>>> ctypes.c_ubyte * 3
<class '__main__.c_ubyte_Array_3'>
...which can be constructed with the same number of arguments...
>>> (ctypes.c_ubyte * 3)(0, 1, 2)
<__main__.c_ubyte_Array_3 object at 0x7fe51e0fa710>
...or you can use the *
operator to call it with the contents of a list...
>>> (ctypes.c_ubyte * 3)(*range(3))
<__main__.c_ubyte_Array_3 object at 0x7fe51e0fa7a0>
...so you'd need something like...
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)
Upvotes: 1