如何将 numpy ND 数组转换为 CFFI C++ 数组并再次转换回来?

How do I convert a numpy ND-array to a CFFI C++ array and back again?

我想通过 CFFI 将一个 numpy 数组传递到某些(其他人的)C++ 代码中。假设我不能(在任何意义上)更改 C++ 代码,其接口是:

double CompactPD_LH(int Nbins, double * DataArray, void * ParamsArray ) {
    ...
}

我将 Nbins 作为 python 整数传递,将 ParamsArray 作为 dict -> 结构传递,但是 DataArray (shape = 3 x NBins,需要从 numpy 数组填充,这让我很头疼。 (来自 Why is cffi so much quicker than numpy? 的 cast_matrix 在这里没有帮助 :(

这是一次失败的尝试:

from blah import ffi,lib
data=np.loadtxt(histof)
DataArray=cast_matrix(data,ffi) # see 
result=lib.CompactPD_LH(Nbins,DataArray,ParamsArray)

作为参考,cast_matrix 是:

def cast_matrix(matrix, ffi):
    ap = ffi.new("double* [%d]" % (matrix.shape[0]))
    ptr = ffi.cast("double *", matrix.ctypes.data)
    for i in range(matrix.shape[0]):
        ap[i] = ptr + i*matrix.shape[1]
    return ap 

还有:

How to pass a Numpy array into a cffi function and how to get one back out?

https://gist.github.com/arjones6/5533938

谢谢@morningsun!

dd=np.ascontiguousarray(data.T)
DataArray = ffi.cast("double *",dd.ctypes.data)
result=lib.CompactPD_LH(Nbins,DataArray,ParamsArray)

有效!