Edu*_*bay 11 arrays fortran function-pointers
我可以在Fortran 90中创建函数指针,代码类似
real, external :: f
Run Code Online (Sandbox Code Playgroud)
然后f用作另一个函数/子例程的参数.但是,如果我想要一个函数指针数组怎么办?在CI中就是这样
double (*f[])(int);
Run Code Online (Sandbox Code Playgroud)
创建一个返回double并取整数参数的函数数组.我试过最明显的,
real, external, dimension(3) :: f
Run Code Online (Sandbox Code Playgroud)
但是gfortran并没有让我混合EXTERNAL和DIMENSION.有什么办法可以做我想要的吗?(这个上下文是一个求解微分方程组的程序,所以我可以在子程序中输入方程而没有一百万个参数.)
M. *_* B. 17
声明"real,external :: f"并没有真正将"f"变成一个完整的指针,因为你无法改变它指向的过程 - 它允许你将这个单一的函数传递给另一个例程.你还需要"指针"属性.Metcalf,Reid&Cohen在"Fortran 95/2003解释"的第267页上有一些例子 - 谷歌搜索"fortran程序指针"将调出此页面.一个接近你的简单例子是"real,external,pointer :: f_ptr".或者:"procedure(f),pointer :: f_ptr".这是Fortran 2003的一个功能 - http://gcc.gnu.org/wiki/Fortran2003和http://gcc.gnu.org/wiki/ProcedurePointers列出了gfortran中的部分支持,最好用4.5.我不确定是否直接允许"维度",但您可以为指针分配一个过程,这提供了很大的灵活性.您还可以将指针放入派生类型,该类型可以制作成数组.
编辑:这是一个代码示例,它适用于gfortran 4.5:编辑2:行注释掉下面的评论.
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
Run Code Online (Sandbox Code Playgroud)