【问题标题】:Using fortran to pass functions into a subroutine.使用 fortran 将函数传递到子例程中。
【发布时间】:2014-02-12 23:33:22
【问题描述】:

我已经编写了一组子例程并将它们编译到一个库中。这些子程序基于一些定义的函数(x,y)。目前这被隐藏在库例程中 - 但是我想要能够将任何函数(x,y)传递到这个库中 - 这可能吗?谢谢大家!

【问题讨论】:

标签: function fortran subroutine


【解决方案1】:
module ExampleFuncs

   implicit none

abstract interface
   function func (z)
      real :: func
      real, intent (in) :: z
   end function func
end interface


contains


subroutine EvalFunc (aFunc_ptr, x)

   procedure (func), pointer :: aFunc_ptr
   real, intent (in) :: x

   write (*, *)  "answer:", aFunc_ptr (x)

end subroutine EvalFunc


function f1 (x)
  real :: f1
  real, intent (in) :: x

  f1 = 2.0 * x

end function f1


function f2 (x)
   real :: f2
   real, intent (in) :: x

   f2 = 3.0 * x**2

end function f2

end module ExampleFuncs


program Func_to_Sub

   use ExampleFuncs

   implicit none

   procedure (func), pointer :: f_ptr => null ()

   f_ptr => f1
   call EvalFunc (f_ptr, 2.0)

   f_ptr => f2
   call EvalFunc (f_ptr, 2.0)

   stop

end program Func_to_Sub

【讨论】:

  • 这不需要用指针来完成。当使用一致的接口声明相应的虚拟参数时,您可以直接传递过程名称。但是指针也可以。
  • 这也可以在没有抽象接口的情况下完成,只需声明 EXTERNAL 对应于函数的参数(据我所知,通过参数传递过程是一个非常古老的 Fortran 功能,在 F66 中已经可用例如)。当然,asbtract 接口 (F2003) 是一种更安全的解决方案,可以避免将错误的过程传递给 EvalFunc。
  • 谢谢大家。那么在上面的例子中,函数 f1 和 f2 可以在程序中定义吗?即,如果模块 ExampleFuncs 是用户所关心的库/黑盒,他们可以在程序或单独的模块中定义函数吗?并调用 ExampleFuncs。这有意义吗?
  • 当然。编辑示例并尝试一下。只需将函数的抽象接口放在模块used 中,以便您可以使用它来声明函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 2018-01-15
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多