ctypes
lib.c
/* sum of a list of doubles */
double sum(double *data, int n)
{
int i=0;
double sum=0.0;
for (i=0; i<n; i++)
{
sum += data[i];
}
return sum;
}
/* mean of a list of doubles */
double mean(double *data, int n)
{
double s = sum(data, n);
return s/((double)n);
}
gcc -shared -fPIC lib.c -o lib.so
test.py
from ctypes import *
so = cdll.LoadLibrary("/home/barnix/py/ctypes/ex1/lib.so")
# Set up interfaces
so.mean.argtypes= [POINTER(c_double), c_int]
so.mean.restype = c_double
so.sum.argtypes = [POINTER(c_double), c_int]
so.sum.restype = c_double
# Call the functions.
def cmean(dlist):
doubleArray = c_double*len(dlist) # Data Type (double[n])
cx = doubleArray(*dlist) # Actual array
n = len(cx) # Length of the data
result = so.mean(cx, n)
return float(result)
def csum(dlist):
doubleArray = c_double*len(dlist)
cx = doubleArray(*dlist)
n = len(cx)
result = so.sum(cx, n)
return float(result)
# We can now use the functions as if they were pure python!
data = [1,2,3,4,5,6]
print cmean(data)
print csum(data)
#((void *) -1)
print c_void_p(-1).value