【问题标题】:How to return a value from a Python callback in Fortran using F2Py如何使用 F2Py 从 Fortran 中的 Python 回调中返回值
【发布时间】:2013-11-28 12:03:40
【问题描述】:

考虑以下 Fortran 子例程,在 test.f 中定义:

subroutine test(py_func)

use iso_fortran_env, only stdout => output_unit

external py_func

integer :: a
integer :: b

a = 12
write(stdout, *) a

b = py_func(a)
write(stdout, *) b

end subroutine

还有以下 Python 代码,在 call_test.py 中定义:

import test

def func(x):
    return x * 2

test.test(func)

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

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

我希望在运行测试时将其作为输出:

      12
      24

但我实际上明白了:

      12
       0

似乎b 被初始化为默认值,而不是test 的结果。我曾尝试在 Fortran 中使用以下内容:

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

但是在将12 打印到控制台后,我的程序崩溃了。

有什么想法可以在这里发生吗?崩溃的原因将是一个奖励,但我真的只是想在这一点上让一个简单的回调工作。

【问题讨论】:

    标签: callback fortran intel-fortran f2py


    【解决方案1】:

    我不声称自己理解它,我在F2Py forum thread 上找到了答案。添加integer py_funcnot!f2py 为前缀)对我有用:

    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
    
    b = py_func(a)
    write(stdout, *) b
    
    end subroutine
    

    也许这与在分配给 b 之前用于存储结果的临时值需要空间有关?无论如何,它显然是依赖于编译器的,这就解释了为什么它不在你可以在网上其他地方找到的各种 F2Py 回调示例中。

    【讨论】:

    • 您的文件中没有implicit none,因此由于隐式键入规则,py_func 被视为real
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 2016-10-23
    相关资源
    最近更新 更多