use*_*302 5 python fortran f2py
假设我们需要在python程序中调用fortran函数,它返回一些值.我发现以这种方式重写fortran代码:
subroutine pow2(in_x, out_x)
implicit none
real, intent(in) :: in_x
!f2py real, intent(in, out) :: out_x
real, intent(out) :: out_x
out_x = in_x ** 2
return
end
Run Code Online (Sandbox Code Playgroud)
并以这种方式在python中调用它:
import modulename
a = 2.0
b = 0.0
b = modulename.pow2(a, b)
Run Code Online (Sandbox Code Playgroud)
给我们工作的结果.我可以用其他方式调用fortran函数,因为我认为第一种方式有点笨拙吗?
mgi*_*son 10
我认为你只需稍微改变你的f2py函数签名(这out_x
只是intent(out)
而且in_x
只是intent(in)
):
subroutine pow2(in_x, out_x)
implicit none
real, intent(in) :: in_x
!f2py real, intent(in) :: in_x
real, intent(out) :: out_x
!f2py real, intent(out) :: out_x
out_x = in_x ** 2
return
end subroutine pow2
Run Code Online (Sandbox Code Playgroud)
现在编译:
f2py -m test -c test.f90
Run Code Online (Sandbox Code Playgroud)
现在运行:
>>> import test
>>> test.pow2(3) #only need to pass intent(in) parameters :-)
9.0
>>>
Run Code Online (Sandbox Code Playgroud)
请注意,在这种情况下,f2py
能够正确扫描函数的签名而无需特殊!f2py
注释:
!test2.f90
subroutine pow2(in_x, out_x)
implicit none
real, intent(in) :: in_x
real, intent(out) :: out_x
out_x = in_x ** 2
return
end subroutine pow2
Run Code Online (Sandbox Code Playgroud)
编译:
f2py -m test2 -c test2.f90
Run Code Online (Sandbox Code Playgroud)
跑:
>>> import test2
>>> test2.pow2(3) #only need to pass intent(in) parameters :-)
9.0
>>>
Run Code Online (Sandbox Code Playgroud)