Python Ctypes: Convert returned C array to python

2020-08-26 11:28发布

问题:

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]

回答1:

I succeeded solving it using pointers

The solution:

Define the function return type as POINTER(double_c) (as of course, arrays are actually pointers in 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()
list = [weights[i] for i in xrange(ARRAY_SIZE_I_KNOW_IN_ADVANCE)]


标签: python ctypes