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. I have the following Fortran code:
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:
def f(x):
print(x)
return x
Now when I wrap the Fortran code with F2PY and run it from Python, eg like this:
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. 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.?
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. The function then has to be called with Fortran's call
statement (as opposed to o = fun(n,x)
). Apparently, one can also get rid of most of the cf2py
statements. Interestingly, fun
does not have to explicitly be declared as a function with array 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.