Skip to content

Instantly share code, notes, and snippets.

@ivan-krukov
Last active August 29, 2015 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan-krukov/8721928 to your computer and use it in GitHub Desktop.
Save ivan-krukov/8721928 to your computer and use it in GitHub Desktop.
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