I am trying to call some c code generated by the Matlab encoder. Matlab uses a c-structure called emxArray to represent matrices (described here: http://www.mathworks.co.uk/help/fixedpoint/ug/c-code-interface-for-unbounded-arrays-and-structure- fields.html ).
struct emxArray_real_T { double *data; int *size; int allocatedSize; int numDimensions; boolean_T canFreeData; };
I have little ctypes experience and am trying to create an equivalent structure that I can use to pass vectors back and forth for functions defined in c.so
This is where I am still in python ...
class EmxArray(ctypes.Structure): """ creates a struct to match emxArray_real_T """ _fields_ = [('data', ctypes.POINTER(ctypes.c_double)), ('size', ctypes.POINTER(ctypes.c_int)), ('allocatedSize', ctypes.c_int), ('numDimensions', ctypes.c_int), ('canFreeData', ctypes.c_bool)]
However, if I define this:
data = (1.1, 1.2, 1.3, 1.4) L = len(data) x = EmxArray() x.data = (ctypes.c_double * L)(*data) x.data = (ctypes.c_int * 1)(L)
it works
print len(x.data[:L]) for v in x.data[:L]: print v
Edit: I tidied up and accepted Roland's suggestion and can extract data using
data_out = x.data[:L]
I need to further explore if I can successfully use this structure to send and receive data from c code.
Decision
The implementation of the ctypes structure suggested by Roland didn't work - the return values ββwere garbage, I never knew why when I was chasing the python-based lilbil response implementation. I accepted this answer as it was the closest ...
I will write down my decision here, as this can save someone who spends as much time as I have.
Firstly, I created a simple matlab function, which in itself multiplies each element of the function and uses an encoder to compile this with .so. This is imported into python using ctypes. The code is as follows:
import ctypes LIBTEST = '..../dll/emx_test/' EMX = ctypes.cdll.LoadLibrary(LIBTEST + 'emx_test.so') init = EMX.emx_test_initialize()
Output:
In: [1.0, 2.0, 4.0, 8.0, 16.0] Out:[1.0, 4.0, 16.0, 64.0, 256.0]
Thank you all for your time and suggestions.