Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

callback Python from Fortran

Now I am using the f2py to call Python function from Fortran code. I have tried a very easy example but it didn't work.

Fortran90 code:

subroutine foo(fun,r)
external fun
integer ( kind = 4 ) i
real ( kind = 8 ) r
r=0.0D+00
do i= 1,5
    r=r+fun(i)
enddo
end

using the commandline:

f2py -c -m callback callback.f90

Python code:

import callback

def f(i):
    return i * i
print callback.foo(f)

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: `Required argument 'r' (pos 2) not found`
like image 331
lbjx Avatar asked Nov 12 '22 03:11

lbjx


1 Answers

You need to declare r as a return value... this is good Fortran 90 practice anyway. Right now f2py is assuming it is an input value.

subroutine foo(fun,r)
    external fun
    real ( kind = 8 ), intent(out) :: r
    integer ( kind = 4 )           :: i
    r=0.0D+00
    do i= 1,5
        r=r+fun(i)
    enddo
end

f2py uses Fortran's intent directives to determine what is passed to the function and what is returned.

like image 55
SethMMorton Avatar answered Nov 15 '22 10:11

SethMMorton