如何将numpy ND阵列转换为CFFI C ++阵列并再次返回?

时间:2016-06-17 12:23:28

标签: python c++ arrays numpy python-cffi

我想通过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 https://stackoverflow.com/questions/23056057/why-is-cffi-so-much-quicker-than-numpy/23058665#23058665
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

1 个答案:

答案 0 :(得分:2)

谢谢@morningsun!

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

作品!