f2py子程序调用Fortran函数

3

是否可能编写一个Fortran f2py子程序,调用一个调用另一个Fortran函数的Fortran函数?例如:

subroutine hello(a)
    ...
    call  newton(b, c)
    ...
end subroutine hello

subroutine newton (d,e)
    ...
    e=q(d)
    ...
end subroutine newton

real function q(x)
    ...
    q = h(x) + h(x-1)
    ...
end function

real function h(x)
    ...
end function h

非常抱歉出现混乱。我尝试过,但编译时出错...我只需要从Python调用第一个sub,提前感谢。

1个回答

3

f2py可以将Fortran子程序转换为Python函数。但是,当它试图将Fortran函数转换为可调用的Python对象时,会引发错误并崩溃。如果这些函数需要从Python中调用,则必须将它们重写为子程序。但是,由于它们只需要从一个Fortran子程序中调用,所以没有必要。

解决方案是在子程序中包含这些函数,使用contains。下面是一个可行的示例,使用与上面相同的结构:

subs.f

subroutine hello(a,b)
  real(8), intent(in) :: a
  real(8), intent(out) :: b

  call  newton(a, b)

end subroutine hello

subroutine newton (d,e)
  real(8), intent(in) :: d
  real(8), intent(out) :: e

  e=q(d)

  contains
    real(8) function q(x)
    real(8) :: x

    q = h(x) + h(x-1)

    end function

    real(8) function h(x)
    real(8) :: x

    h = x*x-3*x+2

    end function h
end subroutine newton

这个文件可以使用f2py转换为Python可调用的函数,特别是使用“快速方式”在f2py文档中解释的方法,通过在命令行中运行f2py -c subs.f -m fsubs生成一个可调用的共享对象,可以使用import fsubs导入。此模块有一些帮助:

help(fsubs)
# Output
Help on module fsubs:

NAME
    fsubs

DESCRIPTION
    This module 'fsubs' is auto-generated with f2py (version:2).
    Functions:
      b = hello(a)
      e = newton(d)
...

可以看到,fsubs模块包含两个函数:hellonewton,这两个子程序。现在,我们可以使用fsubs.hello(4)从Python中调用hello函数,预期结果为8。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接