'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]



Solution 1:[1]

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 array-pointer, like in C:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1