F2py 无法编译带有私有​​函数的模块

F2py unable to compile module with private functions

我正在使用 f2py 从 Fortran 模块构建 Python 模块。 Fortran 模块包含 不需要 在 Python 模块中可用的私有过程。这是重现问题的代码示例:

module testmodule

  implicit none

  public :: &
       test_sub

  private :: &
       useful_func

contains

  subroutine test_sub()

    !uses the function
    print*, useful_func(3)

  end subroutine test_sub

  function useful_func(in) result(res)
    integer, intent(in) :: in
    integer :: res

    !Does some calculation
    res=in+1

  end function useful_func

end module testmodule

当我编译它时:

f2py -c test.f90 -m test

编译失败并显示以下错误消息:

gfortran:f90: /tmp/tmpXzt_hf/src.linux-x86_64-2.7/test-f2pywrappers2.f90
/tmp/tmpXzt_hf/src.linux-x86_64-2.7/test-f2pywrappers2.f90:7:28:

       use testmodule, only : useful_func
                            1
Error: Symbol « useful_func » referenced at (1) not found in module « testmodule »

似乎 gfortran 试图在模块外使用 private 函数,这当然失败了。

删除 public/private 语句解决了问题(通过使所有函数成为 public),但我觉得这不是一个干净的方法。这些函数不一定要在 Python 中使用,也不应该在 Python 环境中使用。 如果无法修改包含此类声明的 Fortran 脚本怎么办?

简而言之:

使用 f2py 在 Fortran 中管理私有过程的干净方法是什么?

f2py 具有启发式方法来确定要包含在已编译模块中的内容。您可以使用选项 "only" 使其具体化,如

f2py -c -m ff ff.f90 only: test_sub

键入不带选项的 f2py 会为您提供一个有用的选项列表。根据您的需要,您可以考虑使用 Fortran(2003 及更高版本)的 iso_c_binding 功能。