I want to call a c function from python using ctypes. From the documentation I don't understand how to pass pointer to vectors. The function I want to call is:
double f(int n, double* x)
{
int i;
double p=1;
for (i=0; i< n; i ++)
p = p * x[i];
return p;
}
I have modified the function with void pointer, so it becomes f(int, void*)
with an internal cast to double. I do the following:
def f(x):
n = len(x)
libc = '/path/to/lib.so'
cn = c_int(n)
px = pointer(x)
cx = c_void_p(px)
libc.restype = c_double
L = libc.f(cn, cx)
return L
I assume that x is a numpy array, but I am not sure how the numpy array are organized in the memory and if this is the best solution.
Edit:
None of the proposed methods work with my numpy array, maybe it is due to how I am defining the array:
x = np.array([], 'float64')
f = open(file,'r')
for line in f:
x = np.append(x,float(line))
but some of them work if I have an explicit list like [1,2,3,4,5]
, rather than a list that has been defined somewhere else and it is referred as x