Last active
August 29, 2015 13:55
-
-
Save ivan-krukov/8721928 to your computer and use it in GitHub Desktop.
Float array returns with python ctypes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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