Skip to content

Instantly share code, notes, and snippets.

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

Embed
What would you like to do?
Float array returns with python ctypes
numbers.so: numbers.c
gcc --std=c99 -fPIC -c numbers.c
gcc -shared numbers.o -o numbers.so
clean:
rm -f numbers.o numbers.so
#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) {
srand(1);
float * vector = (float *)malloc(n*sizeof(float));
for (int i = 0; i < n; i ++) {
vector[i] = rand();
}
return vector;
}
from ctypes import *
libmathy = CDLL('./numbers.so')
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.