pointers - Fortran 中的过程指针
问题描述
我正在尝试拥有一个通用子例程 event() 和一个指向该通用子例程 event_i 的过程指针。然后我想创建任何子例程(如以下代码中的 hello_wolrd)并指向这个创建的子例程。你能帮我理解为什么第一个代码不起作用而第二个代码起作用吗?我在第一个版本的代码中得到的错误是:Program received signal SIGSEGV: Segmentation fault - invalid memory reference
. 我想使用第一个版本,因为这样我可以在子程序 hello_world 中使用 main 中定义的任何变量,而在第二种情况下,我必须将变量传递给 te 子程序,它不能再被定义为通用子程序 event() ,它没有输入。
第一个版本(不工作)
program foo
implicit none
interface
subroutine event()
end subroutine event
end interface
procedure(event), pointer :: event_i => Null()
event_i => hello_world
call event_i
contains
subroutine hello_world()
print *, 'hello_world'
end subroutine
end program foo
第二版(工作):
program foo
implicit none
interface
subroutine event()
end subroutine event
subroutine hello_world()
end subroutine hello_world
end interface
procedure(event), pointer :: event_i => Null()
event_i => hello_world
call event_i
end program foo
subroutine hello_world()
print *, 'hello_world'
end subroutine
我正在使用 gfortran,编译器版本是
gfortran --version
GNU Fortran (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609
解决方案
这是一个稍微重要的修改,它适用于 gfortran:
program foo
implicit none
abstract interface
subroutine event()
end subroutine event
end interface
procedure(event), pointer :: event_i
procedure(event), pointer :: event_j
event_i => hello_world
event_j => hello_world2
call event_i
call event_j
contains
subroutine hello_world()
print *, 'hello_world'
end subroutine
subroutine hello_world2()
print *, 'HELLO_WORLD'
end subroutine
end program foo