1

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!

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't need to be done with a pointer. You can pass a procedure name directly when the corresponding dummy argument is declared with a consistent interface. But pointers work too.
This can be done also without abstract interface, just in declaring EXTERNAL the argument corresponding to the function (as far as I remember, passing a procedure by argument is a very old Fortran feature, already available in F66 for instance). Of course, the asbtract interface (F2003) is a safer solution which avoid to pass a wrong procedure to EvalFunc.
Thanks guys. So in the example above can the functions f1 and f2 be defined in the program? I.e if the module ExampleFuncs was a library/blackbox as far as the user is concerned they could define the function either in the program or a separate module? and call ExampleFuncs. Does that make sense?
Sure. Edit the example and try it out. Just have the abstract interface of the function in a module used so that you can use it to declare the functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.