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 Answer
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
4 Comments
Steve Lionel
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.
Francois Jacq
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.
user2350366
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?
M. S. B.
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.