Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

ctypes

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]

like image 339
SomethingSomething Avatar asked Oct 23 '14 15:10

SomethingSomething


1 Answers

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)]
like image 60
SomethingSomething Avatar answered Oct 22 '22 12:10

SomethingSomething