繁体   English   中英

如何使用模块向Fortran公开Python回调

[英]How to expose Python callbacks to Fortran using modules

这篇关于F2Py的scipy文档页面说明:

[回调函数]也可以在模块中明确设置。 然后,没有必要将参数列表中的函数传递给Fortran函数。 如果调用python回调函数的Fortran函数本身由另一个Fortran函数调用,则可能需要这样做。

但是,我似乎无法找到如何做到这一点的例子。

考虑以下Fortran / Python组合:

test.f

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

end subroutine

call_test.py

import test

def func(x):
    return x * 2

test.test(func)

使用以下命令编译(英特尔编译器):

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

我必须采取哪些更改才能以模块的形式将func暴露给整个Fortran程序,以便我可以从子例程test内部调用该函数,或者在项目中的任何其他fortran文件中调用任何其他子例程?

以下对我有用。 请注意,没有传递给测试的参数。 python文件如问题中所述。

subroutine test()

use iso_fortran_env, only stdout => output_unit

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

integer :: a
integer :: b

a = 12
write(stdout, *) a

end subroutine

py_func ,然后我将py_func包装在一个子程序中,这样我就可以调用它,而不必在我使用它的每个文件/函数中声明以下内容:

integer y
y = py_func(x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM