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

Python 如何从F2PY中的回调函数获取数组返回?,python,fortran,f2py,Python,Fortran,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),

我正试图用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
myscript.myscript(numpy.array([1,2,3]),f)
现在,当我用F2PY包装Fortran代码并从Python运行它时,例如:

def f(x):
    print(x)
    return x
myscript.myscript(numpy.array([1,2,3]),f)
我得到以下结果:

[1. 2. 3.]
1.00000000
显然,数组被传递到回调函数f,但是当它被传递回时,只有第一个条目被保留。
我需要做什么才能找回整个阵列?i、 e.在Fortran代码中获取变量o,使其包含数组[1,2,3],而不是仅包含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

在Fortran代码中,
o
没有声明为数组,也没有
fun
声明为数组结果。在玩了一些之后,我不确定f2py是否支持这些函数。当我添加一个接口块时,在编译C包装器时,它没有编译,但有一些隐藏的错误。顺便说一句,您声明了
cf2py intent(in),Dimension(n),dependent(n)::x
但是在子例程
x
中是
real*8 x(n)
,这是另一个问题。也许一个简单的解释是:用一个数组结果替换函数,并使用一个子例程?