Skip to content

Instantly share code, notes, and snippets.

@ivan-krukov ivan-krukov/makefile
Last active Aug 29, 2015

What would you like to do?
Float array returns with python ctypes numbers.c
gcc --std=c99 -fPIC -c numbers.c
gcc -shared numbers.o -o
rm -f numbers.o
#include <stdlib.h>
//Notice that this is just the raw stuff - it needs to be wrapped nicely into a python class to support deallocation
float * numbers(int n) {
float * vector = (float *)malloc(n*sizeof(float));
for (int i = 0; i < n; i ++) {
vector[i] = rand();
return vector;
from ctypes import *
libmathy = CDLL('./')
def numbers(n):
libmathy.numbers.argtype = c_int
libmathy.numbers.restype = POINTER(c_float*n)
c_array = libmathy.numbers(c_int(n))
return [ i for i in c_array.contents]
#now you can call your code:
a = numbers(20) #which returns a list of 20 elements
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.