Skip to content
Advertisement

Python Ctypes: Convert returned C array to python list, WITHOUT numpy

I am using Python Ctypes to access some C library.

One of the functions I connected to, returns const *double, which is actually an array of doubles.

When I get the result in Python, how can I convert this array to a python list?

The signature of the C function:

const double *getWeights();

Let’s assume that it returns an array that contains 0.13 and 0.12. I want to get a python List: [0.13, 0.12]

Advertisement

Answer

I succeeded solving it using pointers

The solution:

Define the function return type as POINTER(double_c):

getWeights_function_handler.restype = POINTER(double_c)

When the function returns, you can use the [] operator to access the C array elements (the same operator used in C):

weights = getWeights_function_handler()
mylist = [weights[i] for i in xrange(ARRAY_SIZE_I_KNOW_IN_ADVANCE)]
Advertisement