【发布时间】:2016-10-19 06:54:33
【问题描述】:
我想通过 CFFI 将一个 numpy 数组传递给一些(其他人的)C++ 代码。假设我不能(在任何意义上)更改 C++ 代码,其接口是:
double CompactPD_LH(int Nbins, double * DataArray, void * ParamsArray ) {
...
}
我将 Nbins 作为 python 整数传递,ParamsArray 作为 dict -> 结构传递,但是 DataArray (shape = 3 x NBins,需要从 numpy 数组中填充,这让我很头疼。(cast_matrix from Why is cffi so much quicker than numpy?在这里没有帮助:(
这是一次失败的尝试:
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?
【问题讨论】:
-
好吧,这个
cast_matrix函数是用于“数组数组”,而不是一维数组(double **与double *)。我想你只需要DataArray = ffi.cast("double *", data.ctypes.data)。确保data是 C 连续的。 -
谢谢 - 工作! :)
标签: python c++ arrays numpy python-cffi