calling c from python with ctypes: passing vectors -
i want call c function python using ctypes. documentation don't understand how pass pointer vectors. function want call is:
double f(int n, double* x) { int i; double p=1; (i=0; i< n; ++) p = p * x[i]; return p; }
i have modified function void pointer, becomes f(int, void*)
internal cast double. 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 x numpy array, not sure how numpy array organized in memory , if best solution.
edit:
none of proposed methods work numpy array, maybe due how defining array:
x = np.array([], 'float64') f = open(file,'r') line in f: x = np.append(x,float(line))
but of them work if have explicit list [1,2,3,4,5]
, rather list has been defined somewhere else , referred x
based on @sven marnach's answer:
#!/usr/bin/env python import ctypes import numpy np numpy.ctypeslib import ndpointer libf = ctypes.cdll.loadlibrary('/path/to/lib.so') libf.f.restype = ctypes.c_double libf.f.argtypes = [ctypes.c_int, ndpointer(ctypes.c_double)] def f(a): return libf.f(a.size, np.ascontiguousarray(a, np.float64)) if __name__=="__main__": # slice create non-contiguous array = np.arange(1, 7, dtype=np.float64)[::2] assert not a.flags['c_contiguous'] print(a) print(np.multiply.reduce(a)) print(f(a))
output
[ 1. 3. 5.] 15.0 15.0
removing np.ascontiguousarray()
call produces wrong result (6.0
on machine).
Comments
Post a Comment