2

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

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但是我的程序在打印到控制台后崩溃了。

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

4

1 回答 1

0

我没有声称理解它,我在F2Py 论坛主题上找到了答案。添加integer py_func(以 为前缀!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 回调示例中。

于 2013-12-04T09:26:42.010 回答