【问题标题】:Subroutine argument not passed correctly from Python to Fortran子程序参数未正确从 Python 传递到 Fortran
【发布时间】:2012-06-07 15:38:41
【问题描述】:

我正在使用 f2py 编译一个供 Python 脚本使用的数值模块。我已将代码简化为以下最小示例:

fd.f:

module fd
  ! Double precision real kind
  integer, parameter :: dp = selected_real_kind(15)

contains

subroutine lprsmf(th)
  implicit none
  real(dp) th
  write(*,*) 'th - fd',th
end subroutine lprsmf

end module fd

times.f:

subroutine itimes(th)
  use fd
  implicit none
  real(dp) th

  write(*,*) 'th - it',th
  call lprsmf(th)
end subroutine itimes

reprun.py:

import it

th = 200
it.itimes(th)

编译运行使用的命令如下(注意我在Windows下使用cmd):

gfortran -c fd.f
f2py.py -c -m it --compiler=mingw32 fd.o itimes.f
reprun.py

输出是:

th - it  1.50520876326836550E-163
th - fd  1.50520876326836550E-163

我的第一个猜测是 th 没有正确地从 reprun.py 传递到子程序 itimes。但是,我不理解这种行为,因为代码的完整版本包括其他输入,所有这些都正确传递。从 Fortran 调用 itime 时,我无法让它做同样的事情,所以我假设它与 Python/Fortran 接口有关。谁能提供有关为什么会发生这种行为的任何见解?

编辑:将 reprun.py 中的 th = 200 替换为 th = 200.0 会产生以下输出:

th - it  1.19472349365371216E-298
th - fd  1.19472349365371216E-298

【问题讨论】:

  • 我对 Python 或 f2py 一无所知,但是如果将 th = 200 替换为 th = 200.0 会发生什么?
  • @HighPerformanceMark,见编辑。它仍然是一个垃圾值,但是是一个不同的值。

标签: python fortran f2py


【解决方案1】:

也将您的 times 子例程包装在一个模块中。这是我所做的:

times.f90:

module itime

contains

subroutine itimes(th)
  use fd
  implicit none
  real(dp) th

  write(*,*) 'th - it',th
  call lprsmf(th)
end subroutine itimes

end module

编译并运行:

gfortran -c fd.f90
c:\python27_w32\python.exe c:\python27_w32\scripts\f2py.py -c -m it --compiler=mingw32 fd.f90 itimes.f90

运行 reprun.py:

import it

th = 200
it.itime.itimes(th)

输出:

 th - it   200.00000000000000     
 th - fd   200.00000000000000     

【讨论】:

  • 谢谢,这很有帮助。
  • 玩了一会儿,发现不需要在itimes.f中声明模块,看来关键点是传递fd.f90而不是fd.o给f2py。你知道为什么会这样吗?
  • @astay13 啊,你可能是对的,我只是习惯性地改变了它。不确定,我只尝试将实际的 Fortran 源代码传递给 f2py。我仍然建议始终将代码包装在模块中,这样可以避免很多 Fortran 陷阱。
  • @astay13 -- 您需要传递源代码而不是 .o 文件。基本上,f2py 是一个 fortran 解析器(加上一点),它用 C 代码和 python API 包装你的 fortran 代码。然后它将整个东西编译成一个共享对象(使用它可以在你的系统上找到的任何编译器),它可以由 python 加载。如果你给 f2py 一个目标文件——它还不够复杂,无法对已编译的代码进行逆向工程并生成 python 接口。
  • @mgilson,我一直在获取使用 Fortran 目标文件编译的代码,在我遇到这个问题之前它已经正常工作了一段时间。我认为这与我第一次尝试将real 参数传递到主子例程这一事实有关。
猜你喜欢
  • 2022-01-26
  • 2018-01-21
  • 1970-01-01
  • 2017-08-12
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 2012-07-30
  • 1970-01-01
相关资源
最近更新 更多