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

标签 python c++ arrays numpy python-cffi

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

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

我将 Nbins 作为 python 整数传递,将 ParamsArray 作为字典传递 -> 结构,但是 DataArray(形状 = 3 x NBins,需要从 numpy 数组填充,这让我很头疼。(cast_matrix 来自 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?

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)

有效!

关于python - 如何将 numpy ND 数组转换为 CFFI C++ 数组并再次转换回来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37881503/

相关文章:

c# - ZeroMQ CLRZMQ - 轮询套接字

c++ - 将指针数组传递给函数时遇到问题

c++ - 更改xcode中特定代码字的颜色

php - 从两个不同的表中获取 MySQL 值到一个数组中?

python - 如何在 python 3.4 中检查数组中元素的字符串

python - 使用子进程时如何限制程序的执行时间?

python - Cython 和 deepcopy() 与引用的方法/函数有关。任何替代想法?

python - 正则表达式卡住

c++ - 使用 CImg 编辑 RGB 像素数据 - Visual C++ 2008

c++ - 将二维数组作为参数传递