基于@Sven Marnach的答案:
#!/usr/bin/env pythonimport ctypesimport numpy as npfrom numpy.ctypeslib import ndpointerlibf = ctypes.cdll.LoadLibrary('/path/to/lib.so')libf.f.restype = ctypes.c_doublelibf.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 to create non-contiguous array a = np.arange(1, 7, dtype=np.float64)[::2] assert not a.flags['C_CONTIGUOUS'] print(a) print(np.multiply.reduce(a)) print(f(a))输出量
[ 1. 3. 5.]15.015.0
删除
np.ascontiguousarray()呼叫会产生错误的结果(
6.0在我的机器上)。



