如何使用模块将Python回调暴露给Fortran [英] How to expose Python callbacks to Fortran using modules

查看:154
本文介绍了如何使用模块将Python回调暴露给Fortran的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个scipy文档页面关于F2Py状态:

This scipy documentation page about F2Py states:


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

[Callback functions] may also be explicitly set in the module. Then it is not necessary to pass the function in the argument list to the Fortran function. This may be desired if the Fortran function calling the python callback function is itself called by another Fortran function.



<但是,我似乎无法找到这样做的例子。

However, I can't seem to find an example of how this would be done.

考虑以下Fortran / Python组合:

Consider the following Fortran / Python combination:

test.f
$ b

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

call_test.py:

import test

def func(x):
    return x * 2

test.test(func)

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

Compiled with the following command (Intel compiler):

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

为了将 func 以模块的形式公开给整个Fortran程序,我需要做什么修改,以便我可以从子程序 test 或项目中任何其他fortran文件中的任何其他子例程调用该函数?

What changes would I have to take to expose func to the entire Fortran program in the form of a module, so that I could call the function from inside the subroutine test, or any other subroutine in any other fortran file in the project?

推荐答案

以下工作适合我。注意没有传递给测试的参数。 python文件如问题中所述。

The following worked for me. Note the absence of the parameters passed to test. The python file is as stated in the question.

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

As an aside, I then wrapped py_func in a subroutine so that I could call it without having to declare the following in every file / function I use it:

integer y
y = py_func(x)

这篇关于如何使用模块将Python回调暴露给Fortran的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆