python - 使用 F2PY 将数组从 Python 传递到 Fortran 结果错误=2(与形状相关)

标签 python arrays numpy fortran f2py

我有 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/

相关文章:

python - 使用Python中的OpenCV中的Hu矩进行形状识别

c - 我的二维数组中数字的频率无法正确输出

php - 引用 - 这个错误在 PHP 中意味着什么?

php - 比较嵌套数组

python - 无法将稀疏矩阵写入 csv

numpy - cython 和 numpy : 'cfunc.to_py:65:25: ' ndarray' is not a type identifier'

python - 在单个操作中写入内存

python - 如何使用 unittest 断言断言?

python - 如何确定 Pandas 列是否包含特定值

python - 如何检查列表中是否存在 np.NaN 和/或 None