Reading array returned by c function in ctypes
Question:
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?
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])
Thanks to @falsetru, believe I found a somehow better solution, which takes into account the fact that the C function returns a pointer to two floats:
import ctypes
libfoo = ctypes.cdll.LoadLibrary('./foo.so')
foo = libfoo.foo
foo.argtypes = ()
foo.restype = ctypes.POINTER(ctypes.c_float * 2)
result = foo().contents
print('length of the returned list: ' + len(result))
print(result[0], result[1])
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?
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])
Thanks to @falsetru, believe I found a somehow better solution, which takes into account the fact that the C function returns a pointer to two floats:
import ctypes
libfoo = ctypes.cdll.LoadLibrary('./foo.so')
foo = libfoo.foo
foo.argtypes = ()
foo.restype = ctypes.POINTER(ctypes.c_float * 2)
result = foo().contents
print('length of the returned list: ' + len(result))
print(result[0], result[1])