如何使用SWIG将Fortran有序的2d numpy数组传递到c ++中

How to pass a fortran ordered 2d numpy array into c++ using SWIG

本文关键字:数组 numpy 2d SWIG 何使用 Fortran      更新时间:2023-10-16

我在 c++ 中有一个函数

myfun(double* array, int n1, int n2);

我在 python 中与 numpy 接口。在我的界面文件中,我有

%apply (double* INPLACE_FARRAY2, int DIM1, int DIM2) {(double* inarray, int n1, int n2)}

现在,我想将数组b = array([[3,27.0],[2,9],[10,1]],order='F')传递到 python 中的 myfun 中,但出现以下错误

TypeError: Array must be contiguous.  A non-contiguous array was given. 

我做错了什么?我的 %apply 语句中的双精度数据类型不正确吗?

Fortran 顺序 (order='F') 可能是问题所在,因为这与 C 顺序相反,我不确定,因为我无法找到 numpy 的意外与非的明确定义。因此,可能值得尝试:

b = array([[3,27.0],[2,9],[10,1]],order='C')

另外,可能值得一试

myfun( numpy.ascontiguousarray(b) )

我发现 numpy swig 参考文档有助于理解INPLACE_IN_类型图之间的区别。基本上,当c函数只读取而不写入时,使用后者,只要输入是某种序列,SWIG代码就可以处理它。前者表示 c 函数将写入数组,因此原始容器中的顺序必须匹配。