我有 Fortran 代码,我想使用 f2py 从 Python 提供该代码。但我无法通过 f2py 传递已知形状的 Numpy 数组。 (我使用的是 Python 2.7.10 并使用 gfortran 和 mingw32 作为编译器)。
这是我的 Fortran 代码:
Subroutine test(nx,ny,mask)
Integer, intent(inout) :: mask(ny,nx)
!f2py intent(in,out) mask
End
Python 中的调用方式如下:
from test import test
import numpy as np
nx = 2
ny = 2
mask = np.ones((nx,ny),dtype=int)
maskreturn = test(nx,ny,mask)
运行脚本结果:
error: (shape(mask,1)==nx) failed for 1st keyword nx: test:nx=2
我不知道如何让它运行(我需要正确传递网格以获得更大的模型)。其中是否存在一些可怕的 Fortran Noob 错误?
最佳答案
以下内容似乎对我有用
untitled.f90
中的 Fortran block :
subroutine test(nx,ny,mask)
integer, intent(in) :: nx, ny
integer, dimension(nx,ny), intent(inout) :: mask
!f2py intent(in,out) mask
print*,nx,ny,mask
end subroutine test
编译:
f2py -c --fcompiler=gnu95 untitled.f90
在Python中做:
from untitled import test
import numpy as np
nx = 2 ; ny = 2
mask = np.ones((nx,ny),dtype=np.int32)
temp = test(mask,ny,nx) #Note the reversed order
我希望这会有所帮助,但我没有使用 f2py
的经验,因此无法更多解释为什么它有效。
更新在寻找潜在的重复项后,我发现了 this answer这解释了上述工作原理和原因。
关于python - 使用 F2PY 将数组从 Python 传递到 Fortran 结果错误=2(与形状相关),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37592168/