1

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 ?

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.