How to return value from Python callback to Fortran using F2Py

Consider the following Fortran routine, defined in test.f:

subroutine test(py_func)

use iso_fortran_env, only stdout => output_unit

external py_func

integer :: a
integer :: b

a = 12
write(stdout, *) a

b = py_func(a)
write(stdout, *) b

end subroutine

Also the following Python code defined in call_test.py:

import test

def func(x):
    return x * 2

test.test(func)

Compiled with the following (Intel compiler):

python f2py.py -c test.f --fcompiler=intelvem -m test

I expect this to be the result when running the test:

      12
      24

But I really get the following:

      12
       0

It seems to be binitialized to the default instead of the result test. I tried using the following in Fortran:

!f2py intent(callback) py_func
      external py_func
!f2py integer y,x
!f2py y = py_func(x)

But my program crashes after printing 12on the console.

Any ideas what can be done here? The cause of the disaster will be a bonus, but I'm really just interested in having a simple callback work at that moment.

+2
1

, , F2Py. integer py_func ( !f2py) :

subroutine test(py_func)

use iso_fortran_env, only stdout => output_unit

!f2py intent(callback) py_func
external py_func
integer py_func
!f2py integer y,x
!f2py y = py_func(x)

integer :: a
integer :: b

a = 12
write(stdout, *) a

b = py_func(a)
write(stdout, *) b

end subroutine

, , , b? , , -, , , F2Py, .

0

Source: https://habr.com/ru/post/1620883/


All Articles