Function pointer arrays in Fortran

后端 未结 1 2063
离开以前
离开以前 2020-11-29 04:34

I can create function pointers in Fortran 90, with code like

real, external :: f

and then use f as an argument to another func

1条回答
  •  北海茫月
    2020-11-29 05:00

    The declaration "real, external :: f" doesn't really make "f" into a full pointer since you can't change the procedure that it points -- it does permit you to pass this single function to another routine., So you also need the "pointer" attribute. There are examples on page 267 of "Fortran 95/2003 explained" by Metcalf, Reid & Cohen -- a google search for "fortran procedure pointer" will bring up this page. A simple example close to yours is "real, external, pointer :: f_ptr". Alternatively: "procedure (f), pointer :: f_ptr". This is a Fortran 2003 feature -- http://gcc.gnu.org/wiki/Fortran2003 and http://gcc.gnu.org/wiki/ProcedurePointers lists partial support in gfortran, best with 4.5. I'm not sure whether "dimension" is directly allowed, but you can assign a procedure to a pointer, which provides a lot of flexibility. You can also put the pointer into a derived type, which could be made into an array.

    Edit: here is a code example which works with gfortran 4.5: Edit 2: line commented out per comments below.

    module ExampleFuncs
    
      implicit none
    
    contains
    
    function f1 (x)
      real :: f1
      real, intent (in) :: x
    
      f1 = 2.0 * x
    
      return
    end function f1
    
    
    function f2 (x)
       real :: f2
       real, intent (in) :: x
    
       f2 = 3.0 * x**2
    
       return
    end function f2
    
    
    function fancy (func, x)
    
       real :: fancy
       real, intent (in) :: x
    
       interface AFunc
          function func (y)
             real :: func
             real, intent (in) ::y
          end function func
       end interface AFunc
    
       fancy = func (x) + 3.3 * x
    
    end function fancy
    
    end module  ExampleFuncs
    
    program test_proc_ptr
    
      use ExampleFuncs
    
      implicit none
    
      ! REMOVE: pointer :: func
      interface
         function func (z)
            real :: func
            real, intent (in) :: z
         end function func
      end interface
    
      procedure (func), pointer :: f_ptr => null ()
    
      type Contains_f_ptr
         procedure (func), pointer, nopass :: my_f_ptr
      end type Contains_f_ptr
    
      type (Contains_f_ptr), dimension (2) :: NewType
    
    
      f_ptr => f1
      write (*, *) f_ptr (2.0)
      write (*, *) fancy (f_ptr, 2.0)
    
      f_ptr => f2
      write (*, *) f_ptr (2.0)
      write (*, *) fancy (f_ptr, 2.0)
    
      NewType(1) % my_f_ptr => f1
      NewType(2) % my_f_ptr => f2
    
      write (*, *) NewType(1) % my_f_ptr (3.0), NewType(2) % my_f_ptr (3.0)
    
      stop
    
    end program test_proc_ptr
    

    0 讨论(0)
提交回复
热议问题