How make external function work with f2py?

Viewed 90

I am trying to compile a piece of old Fortran code with f2py so that it can be called within Python. However, there is a part involving external function that wouldn’t work. Here is a minimal working example, first the test.f:

      function f(x)
      implicit double precision (a-z)

      f = x * x

      return
      end function f

      subroutine gauss(fun)
      implicit double precision (a-h, j-z)
      ! external fun

      x = 1.5
      write(*,*) fun(x)

      return
      end subroutine gauss

And after compiled with makefile

f2py -c --quiet --fcompiler=gnu95 \
        --f90flags=“-Wtabs” \
        -m test \
        test.f

I call it from Python using

import test
f = lambda x: x
test.gauss(test.f)

and get the error TypeError: test.gauss() 1st argument (fun) can’t be converted to double.

In an second attempt, I uncomment the line external fun in the subroutine gauss and get the following error message during compilation

/tmp/tmpet9sk3e9/src.linux-x86_64-3.7/testmodule.c: In function ‘cb_fun_in_gauss__user__routines’:
/tmp/tmpet9sk3e9/src.linux-x86_64-3.7/testmodule.c:313:8: error: variable or field ‘return_value’ declared void

I am now out of ideas, any help will be greatly appreciated!

1 Answers

I have (partly) figured it out: f2py needs you to explicitly specify the use of the function. Here is how:

      function f(x)
      implicit double precision (a-z)

      f = x * x

      return
      end function f

      subroutine gauss(fun)
      implicit double precision (a-h, j-z)
      !! <-------- updates starts HERE
      external fun
!f2py real*8 y
!f2py y = fun(y)
      double precision fun
      !! <-------- updates ends HERE

      x = 1.5
      write(*,*) fun(x)

      return
      end subroutine gauss

then compile it using

main:
    f2py -c --quiet --fcompiler=gnu95 \
        --f90flags=“-Wtabs” \
        -m test \
        test.f

You can test with

import test
f = lambda x: x
test.gauss(test.f)
test.gauss(f)

and see that the external function works for both Fortran and Python functions.


Two side notes:

  1. Although the documentation says !f2py intent(callback) fun is necessary, I find the code can work without it.
  2. You can specify multiple external functions using the same syntax, you can even use the same dummy input variable y for all of them (maybe not a good practice though).
Related