【问题标题】:How to get array return from callback function in F2PY?如何从 F2PY 中的回调函数中获取数组返回?
【发布时间】:2015-08-10 15:23:56
【问题描述】:

我正在尝试使用 F2PY 编写一个从 Python 到 Fortran 的小接口,其中一个数组被传递给 Python 中的回调函数,结果数组被传递回 Fortran。 我有以下 Fortran 代码:

      Subroutine myscript(x,fun,o,n)
      external fun
      integer n
      real*8 x(n)
cf2py intent(in,copy) x
cf2py intent(out) o
cf2py integer intent(hide),depend(x) :: n=shape(x,0)
cf2py function fun(n,x) result o
cf2py integer intent(in,hide) :: n
cf2py intent(in), Dimension(n), depend(n) :: x
cf2py end function fun
      o = fun(n,x)
      write(*,*) o
      end

其中 fun 是 Python 中的回调函数,如下所示:

def f(x):
    print(x)
    return x

现在,当我使用 F2PY 包装 Fortran 代码并从 Python 运行它时,例如像这样:

myscript.myscript(numpy.array([1,2,3]),f)

我得到以下结果:

[1. 2. 3.]
1.00000000

显然,数组被传递给回调函数 f,但是当它被传回时,只有第一个条目被保留。 我需要做什么才能让整个阵列恢复原状?即在 Fortran 代码中获取变量 o 以包含数组 [1.,2.,3.] 而不是 1.?

【问题讨论】:

  • o 在 Fortran 代码中未声明为数组,fun 也未声明为数组结果。
  • 玩了一段时间后,我不确定 f2py 是否支持这些功能。当我添加一个接口块时,在编译 C 包装器时它没有编译并出现一些神秘的错误。
  • 顺便说一句,您声明了cf2py intent(in), Dimension(n), depend(n) :: x,但在子程序中xreal*8 x(n),这是另一个问题。

标签: python fortran f2py


【解决方案1】:

好吧,我终于想通了。正如所指出的,o 必须被声明,然后o 也必须被放入函数fun 中。然后必须使用 Fortran 的 call 语句(而不是 o = fun(n,x))调用该函数。显然,也可以摆脱大部分cf2py 语句。有趣的是,fun 不必显式声明为返回数组的函数。以下代码适用于我:

      Subroutine myscript(x,fun,o,n)
      external fun
      integer n
      real*8 x(n)
      real*8 o(n)
cf2py intent(in,copy), depend(n) :: x
cf2py intent(hide) :: n
cf2py intent(out), depend(n) :: o
      call fun(n,x,o)
      write(*,*) o
      end

返回

[1. 2. 3.]
1.00000000 2.00000000 3.00000000

【讨论】:

  • 也许一个简单的澄清可以是:用一个子程序替换一个数组结果的函数?
猜你喜欢
  • 2013-07-02
  • 1970-01-01
  • 2020-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-28
  • 2015-12-03
  • 1970-01-01
相关资源
最近更新 更多