【问题标题】:How do I convert a numpy ND-array to a CFFI C++ array and back again?如何将 numpy ND 数组转换为 CFFI C++ 数组并再次返回?
【发布时间】: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?

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

【问题讨论】:

  • 好吧,这个cast_matrix 函数是用于“数组数组”,而不是一维数组(double **double *)。我想你只需要DataArray = ffi.cast("double *", data.ctypes.data)。确保 data 是 C 连续的。
  • 谢谢 - 工作! :)

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


【解决方案1】:

谢谢@morningsun!

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

有效!

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    相关资源
    最近更新 更多