Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading array returned by c function in ctypes

Tags:

python

c

ctypes

I've got some C code, which I'm trying to access from ctypes in python. A particular function looks something like this:

float *foo(void) {
    static float bar[2];
    // Populate bar
    return bar;
}

I know this isn't an ideal way to write C, but it does the job in this case. I'm struggling to write the python to get the two floats contained in the response. I'm fine with return values that are single variables, but I can't work out from the ctypes docs how to handle a pointer to an array.

Any ideas?

like image 967
TimD Avatar asked Aug 04 '13 15:08

TimD


1 Answers

Specify restypes as [POINTER][1](c_float):

import ctypes

libfoo = ctypes.cdll.LoadLibrary('./foo.so')
foo = libfoo.foo
foo.argtypes = ()
foo.restype = ctypes.POINTER(ctypes.c_float)
result = foo()
print(result[0], result[1])
like image 109
falsetru Avatar answered Nov 14 '22 08:11

falsetru