简体   繁体   English

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

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

I'm trying to write a little interface from Python to Fortran with F2PY, where an array gets passed to a callback function in Python and the resulting array gets passed back to Fortran. 我正在尝试使用F2PY从Python到Fortran编写一个小接口,其中将数组传递给Python中的回调函数,然后将所得的数组传递回Fortran。 I have the following Fortran code: 我有以下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

where fun is a callback function in Python which looks like this: 其中fun是Python中的回调函数,如下所示:

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

Now when I wrap the Fortran code with F2PY and run it from Python, eg like this: 现在,当我用F2PY包装Fortran代码并从Python运行它时,例如:

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

I get the following result: 我得到以下结果:

[1. 2. 3.]
1.00000000

So apparently the array gets passed through to the callback function f but then when it gets passed back only the first entry is preserved. 因此,很显然,该数组将传递给回调函数f,但随后将其传递回时,仅保留第一个条目。 What do I need to do to get the whole array back? 我需要做些什么来取回整个阵列? ie get the variable o in the Fortran Code to contain the array [1.,2.,3.] instead of just 1.? 即在Fortran代码中获取变量o包含数组[1.,2.,3。]而不是仅包含1。

Okay, I finally figured it out. 好吧,我终于明白了。 As pointed out, o has to be declared and then o has to be put into the function fun too. 正如指出的那样, o必须声明,然后o已投入功能fun了。 The function then has to be called with Fortran's call statement (as opposed to o = fun(n,x) ). 然后必须使用Fortran的call语句(而不是o = fun(n,x) )来调用该函数。 Apparently, one can also get rid of most of the cf2py statements. 显然,人们也可以摆脱大多数cf2py语句。 Interestingly, fun does not have to explicitly be declared as a function with array return. 有趣的是,不必将fun明确声明为具有数组return的函数。 The following code works for me: 以下代码对我有用:

      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

It returns 它返回

[1. 2. 3.]
1.00000000 2.00000000 3.00000000

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

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