如何在Fortran中将子例程名称作为参数传递?

时间:2015-09-27 15:46:44

标签: fortran subroutine

将子例程名称作为参数传递的语法是什么?示意性地:

  .
  .
call action ( mySubX ( argA, argB ) )
  .
  .

subroutine action ( whichSub ( argA, argB ) )
  ...
call subroutine whichSub ( argA, argB )
  ...
end subroutine action

目标是让call subroutine whichSub ( argA, argB )充当call subroutine mySubX ( argA, argB )。 我的首选是避免传递switch参数,然后使用SELECT CASE。

2 个答案:

答案 0 :(得分:12)

call action(mySubX)

提供的操作视为

subroutine action(sub)
  !either - not recommmended, it is old FORTRAN77 style
  external sub
  !or - recommended
  interface
    subroutine sub(aA, aB)
      integer,intent(...) :: aA, aB
    end subroutine
  end interface
  ! NOT BOTH!!

  call sub(argA, argB)

已提供action知道将argA, argB放在哪里以表示aA, aB

否则,如果你想传递参数

call action(mySubX, argA, argB)

subroutine action(sub, argA, argB)
  !either - not recommmended, it is old FORTRAN77 style
  external sub
  !or - recommended
  interface
    subroutine sub(aA, aB)
      integer,intent(...) :: aA, aB
    end subroutine
  end interface

  integer, intent(...) :: argA, argB

  call sub(argA, argB)

我不认为在这里使用函数指针是好的,当你必须有时改变指针的值(它指向的子程序)时,它们是好的。正常的过程参数在FORTRAN77中起作用,并且即使现在也继续有效。

因此,根据注释中的要求,如果您在模块中并且可以从模块(可能在同一模块中)访问具有正确接口的过程,则可以使用procedure语句获取接口块的rod:< / p>

module subs_mod
contains
  subroutine example_sub(aA, aB)
    integer,intent(...) :: aA, aB
    !the real example code
  end subroutine
end module

module action_mod
contains

  subroutine action(sub)
    use subs_mod
    procedure(example_sub) :: sub

    call sub(argA, argB)
  end subroutine
end module

但更有可能的是,您将创建一个抽象接口,而不是真正的子例程,您将使用过程语句引用它,因此最终所有内容都与之前类似:

module action_mod

  abstract interface
    subroutine sub_interface(aA, aB)
      integer,intent(...) :: aA, aB
    end subroutine
  end interface

contains

  subroutine action(sub)
    procedure(sub_interface) :: sub

    call sub(argA, argB)
  end subroutine
end module

答案 1 :(得分:2)

我认为使用模块来避免interface是一个很好的现代Fortran实践,因为它提供了更清晰的界面。

这是理想的意识:

模块部分:

module foo
contains

subroutine callsub(sub,arg1,arg2)
!This subroutine is used to call other subroutines
external::sub !Use external to tell compiler this is indeed a subroutine
call sub(arg1,arg2)
end subroutine

subroutine sub(arg1,arg2)
!The subroutine to be called.
!do something
end sub

end module

然后这是主程序:

program main
use foo !Use module automatically avoids using interface.
implicit none
!Declare about args
call callsub(sub,arg1,arg2)
end program

以下是my demonstration,以确切了解如何实现这一目标。