繁体   English   中英

如何从F2PY中的回调函数获取数组返回?

[英]How to get array return from callback function in F2PY?

我正在尝试使用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必须声明,然后o已投入功能fun了。 然后必须使用Fortran的call语句(而不是o = fun(n,x) )来调用该函数。 显然,人们也可以摆脱大多数cf2py语句。 有趣的是,不必将fun明确声明为具有数组return的函数。 以下代码对我有用:

      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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM