问题
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