Search code examples
pythonfortranf2py

combining python with fortran, trouble with tutorial


I'm following this tutorial http://www.sam.math.ethz.ch/~raoulb/teaching/PythonTutorial/combining.html

I use the same code

      program hwtest
      real*8 r1, r2 ,s
      r1 = 1.0
      r2 = 0.0
      s = hw1(r1, r2)
      write(*,*) 'hw1, result:',s
      write(*,*) 'hw2, result:'
      call hw2(r1, r2)
      call hw3(r1, r2, s)
      write(*,*) 'hw3, result:', s
      end

      real*8 function hw1(r1, r2)
      real*8 r1, r2
      hw1 = sin(r1 + r2)
      return
      end

      subroutine hw2(r1, r2)
      real*8 r1, r2, s
      s = sin(r1 + r2)
      write(*,1000) 'Hello, World! sin(',r1+r2,')=',s
 1000 format(A,F6.3,A,F8.6)
      return
      end

C     special version of hw1 where the result is
C     returned as an argument:

      subroutine hw3_v1(r1, r2, s)
      real*8 r1, r2, s
      s = sin(r1 + r2)
      return
      end

C     F2py treats s as input arg. in hw3_v1; fix this:

      subroutine hw3(r1, r2, s)
      real*8 r1, r2, s
Cf2py intent(out) s
      s = sin(r1 + r2)
      return
      end

C     test case sensitivity:

      subroutine Hw4(R1, R2, s)
      real*8 R1, r2, S
Cf2py intent(out) s
      s = SIN(r1 + r2)
      ReTuRn
      end

C end of F77 file

but when I use the command

f2py -m hw -c ../hw.f

I get the following error:

gfortran:f77: ../hw.f
../hw.f:5.13:

      s = hw1(r1, r2)                                                   
             1
Error: Return type mismatch of function 'hw1' at (1) (REAL(4)/REAL(8))
../hw.f:5.13:

      s = hw1(r1, r2)                                                   
             1
Error: Return type mismatch of function 'hw1' at (1) (REAL(4)/REAL(8))
error: Command "/usr/bin/gfortran -Wall -ffixed-form -fno-second-underscore -fPIC -O3 -funroll-loops -I/tmp/tmpRGHzqj/src.linux-x86_64-2.7 -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c -c ../hw.f -o /tmp/tmpRGHzqj/fortran/hw.o" failed with exit status 1

I have no experience with Fortran, I only need to implement existing Fortran code to use in Python.


Solution

  • The interface for hw1 is missing in your code. Either specify it explicitly:

    program hwtest
      real*8 r1, r2 ,s
      real*8 hw1
    c [...]
    

    Or, even better, put the functions into a module, and use the module.

    BTW: Change *8 by something better suited, like:

    program hwtest
      integer,parameter :: dp = kind(1.d0)
      real(dp) r1, r2 ,s
      real(dp) hw1
    

    Or, use ISO_Fortran_env, and the pre-defined parameters REAL64 and REAL32.