来自 Fortran 的回调 Python

Xia*_*iao 5 python callback fortran90 f2py

现在我正在使用f2pyFortran 代码调用 Python 函数。我尝试了一个非常简单的例子,但没有成功。

Fortran90代码:

subroutine foo(fun,r)
external fun
integer ( kind = 4 ) i
real ( kind = 8 ) r
r=0.0D+00
do i= 1,5
    r=r+fun(i)
enddo
end
Run Code Online (Sandbox Code Playgroud)

使用命令行:

f2py -c -m 回调callback.f90

Python代码:

import callback

def f(i):
    return i * i
print callback.foo(f)
Run Code Online (Sandbox Code Playgroud)

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: `Required argument 'r' (pos 2) not found`
Run Code Online (Sandbox Code Playgroud)

Set*_*ton 1

您需要声明r为返回值...无论如何,这是很好的 Fortran 90 实践。现在f2py假设它是一个输入值。

subroutine foo(fun,r)
    external fun
    real ( kind = 8 ), intent(out) :: r
    integer ( kind = 4 )           :: i
    r=0.0D+00
    do i= 1,5
        r=r+fun(i)
    enddo
end
Run Code Online (Sandbox Code Playgroud)

f2py使用 Fortran 的意图指令来确定传递给函数的内容以及返回的内容。