Subroutine argument not passed correctly from Python to Fortran

£可爱£侵袭症+ 提交于 2019-12-10 10:07:06

问题


I am using f2py to compile a numerical module for use by a Python script. I have reduced my code to the minimal example below:

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

itimes.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)

The commands used to compile and run are as follows (Note that I am using cmd under Windows):

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

The output is:

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

My first guess is that th is somehow not being passed correctly from reprun.py to subroutine itimes. However, I do not understand this behavior, as the full version of the code includes other inputs, all of which are passed correctly. I was not able to get it to do the same thing when calling itimes from Fortran, so I'm assuming it has something to do with the Python/Fortran interface. Can anyone provide any insights into why this behavior occurs?

EDIT: Replacing th = 200 in reprun.py with th = 200.0 yields the following output:

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

回答1:


Wrap your itimes subroutine in a module as well. Here is what i did:

itimes.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

compile & run:

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

run reprun.py:

import it

th = 200
it.itime.itimes(th)

output:

 th - it   200.00000000000000     
 th - fd   200.00000000000000     


来源:https://stackoverflow.com/questions/10935126/subroutine-argument-not-passed-correctly-from-python-to-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!