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!
Asked
Active
Viewed 206 times
1
-
1Yes, pass a procedure / function pointer. See http://stackoverflow.com/questions/8612466/how-to-alias-a-function-name-in-fortran – M. S. B. Feb 13 '14 at 00:24
1 Answers
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

M. S. B.
- 28,968
- 2
- 46
- 73
-
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. – Steve Lionel Feb 13 '14 at 14:15
-
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. – Francois Jacq Feb 15 '14 at 02:28
-
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? – user2350366 Feb 16 '14 at 00:53
-
Sure. Edit the example and try it out. Just have the abstract interface of the function in a module `use`d so that you can use it to declare the functions. – M. S. B. Feb 16 '14 at 02:13