user2350366
user2350366

Reputation: 511

Using fortran to pass functions into a subroutine.

I've written a set of subroutines and compiled them into a library. These subroutines are based on some defined function(x,y). At the moment this is buried inside the library routine - however what I'd like is to be able to pass any function(x,y) into this library - is this possible? Thanks guys!

Upvotes: 1

Views: 273

Answers (1)

M. S. B.
M. S. B.

Reputation: 29391

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

Upvotes: 1

Related Questions