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

2024-04-10

这个 scipy 文档页面 http://docs.scipy.org/doc/numpy-dev/f2py/python-usage.html#call-back-arguments关于 F2Py 指出:

[回调函数]也可以在模块中显式设置。然后 没有必要将参数列表中的函数传递给 Fortran 函数。如果 Fortran 函数调用,这可能是需要的 python回调函数本身被另一个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

呼叫测试.py:

import test

def func(x):
    return x * 2

test.test(func)

使用以下命令编译(Intel编译器):

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在子例程中,以便我可以调用它,而不必在我使用它的每个文件/函数中声明以下内容:

integer y
y = py_func(x)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用模块向 Fortran 公开 Python 回调 的相关文章

随机推荐