Fortran中如何将subroutine作为参数传递给另一个subroutine
在Fortran中传递Subroutine作为参数的实现方法
要实现将subroutine作为参数传递给另一个subroutine,核心是通过**抽象接口(abstract interface)**定义被传递子例程的签名约束,再用该接口声明接收方的子例程参数。以下是针对你代码的具体修改方案:
关键修改说明
- 在通用模块
mod2中,先定义与目标子例程(如sub1)参数签名匹配的抽象接口,明确参数类型、intent和数量; - 用这个抽象接口来声明
sub2中接收子例程的参数other_sub。
完整可运行代码
mod1.f90(无需修改)
module mod1 implicit none public sub1 contains subroutine sub1(arg1, arg2) real, intent(in) :: arg1 real, intent(out) :: arg2 arg2 = sqrt(arg1) end subroutine sub1 end module mod1
修改后的mod2.f90
module mod2 implicit none public sub2 ! 定义抽象接口,匹配被传递子例程的参数签名 abstract interface subroutine SubroutineTemplate(arg1, arg2) real, intent(in) :: arg1 real, intent(out) :: arg2 end subroutine SubroutineTemplate end interface contains subroutine sub2(other_sub, arg1, arg2) ! 使用抽象接口声明子例程类型参数 procedure(SubroutineTemplate) :: other_sub real, intent(in) :: arg1 real, intent(inout) :: arg2 call other_sub(arg1, arg2) arg2 = exp(arg2) end subroutine sub2 end module mod2
main.f90(无需修改)
program main use mod1, only : sub1 use mod2, only : sub2 implicit none real :: a, b a = 0.2 call sub2(sub1, a, b) print *, b, exp(sqrt(a)) end program main
编译运行
使用你原本的编译命令即可:
gfortran mod1.f90 mod2.f90 main.f90 ./a.out # Linux/macOS环境运行 a.exe # Windows环境运行
运行后会输出两个完全相等的数值,验证逻辑正确性。
补充说明
- 抽象接口的作用是强约束被传递子例程的签名,避免类型、参数数量或intent不匹配的编译错误;
- 若需要支持多类不同签名的子例程,可定义多个抽象接口,或结合泛型特性扩展;
- 这和Python中传递函数的逻辑本质类似,但Fortran作为静态类型语言,必须显式声明接口约束,而Python依赖动态类型检查。
内容的提问来源于stack exchange,提问作者jared
相关产品推荐
相关产品推荐

