如何在 Fortran 中将子例程名称作为参数传递? [英] How to pass subroutine names as arguments in Fortran?
问题描述
将子例程名称作为参数传递的语法是什么?示意图:
What is the syntax for passing subroutine names as arguments? Schematically:
.
.
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)
.我的偏好是避免传递开关参数,然后使用 SELECT CASE.
The goal is to have call subroutine whichSub ( argA, argB )
act as call subroutine mySubX ( argA, argB )
.
My preference is to avoid avoid passing a switch parameter and then use SELECT CASE.
推荐答案
是的
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
.
provided action
knows what to put there as argA, argB
to represent aA, aB
.
否则,如果您还想传递参数
Otherwise, if you want to pass also the arguments
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 中有效,并且即使现在也继续有效.
I don't think it is good to use function pointers here, they are good when you have to change the value of the pointer (the subroutine it points to) sometimes. Normal procedure arguments worked in FORTRAN77 and continue to work even now.
所以按照评论中的要求,如果你在一个模块中并且可以从模块中访问具有正确接口的过程(可能在同一个模块中),你可以使用过程语句来获取接口块的棒:
So as requested in the comment, if you are in a module and procedure with the right interface is accessible from the module (perhaps in the same module), you can use the procedure statement to get rod of the interface block:
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
但更有可能的是,您将创建一个抽象接口,而不是一个真正的子例程,您将使用过程语句引用该接口,因此最终一切都将与以前相似:
but more likely, instead of a real subroutine you will create an abstract interface which you would reference with the procedure statement so in the end everything will be similar as before:
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
这篇关于如何在 Fortran 中将子例程名称作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!