2014-02-17 34 views
5

This scipy documentation page约F2Py状态,以暴露的Python回调的Fortran:如何使用模块

[回调函数]也可以在模块中被显式地设置。然后, 不需要将参数列表中的函数传递给 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 

call_test.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文件中的任何其他子程序内调用函数该项目?

+0

这里并模块代码帮助? https://code.google.com/p/f2py/wiki/FAQ2ed它看起来好像是新模块创建的,尽管我有点困惑它是python模块还是fortran模块。 –

+0

对不起,忘了添加我发现这个问题的答案。你的评论提醒了我。见下文。 – JimmidyJoo

回答

2

以下为我工作。注意没有传递给测试的参数。 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)