Fortran中的过程指针 [英] Procedure pointers in Fortran

查看:114
本文介绍了Fortran中的过程指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图拥有一个通用子例程event()和一个指向该通用子例程event_i的过程指针.然后,我想创建任何子例程(如以下代码中的hello_wolrd)并指向此已创建的子例程.您能帮我理解为什么第一个代码不起作用而第二个代码却起作用吗?我在第一版代码中遇到的错误是:Program received signal SIGSEGV: Segmentation fault - invalid memory reference.我想使用第一个版本,因为这样我就可以在子例程hello_world中使用main中定义的任何变量,而在第二种情况下,我必须将该变量传递给te子例程,并且不能再将其定义为通用子例程event() ,它没有输入.

I am trying to have a generic subroutine event() and a procedure pointer to this generic subroutine, event_i. Then I would like to create any subroutine (like hello_wolrd in the following code) and point to this created subroutine. Can you help me to understand why the first code does not work while the second one does work? The error I get with the first version of the code is: Program received signal SIGSEGV: Segmentation fault - invalid memory reference. I would like to use the first version because then I can use inside the subroutine hello_world any variable defined in the main while in the second case I have to pass the variable to te subroutine and it cannot be defined anymore as a generic subroutine event(), which does not have input.

第一个版本(不起作用)

First version(not working)

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,编译器版本为

I am using gfortran and the compiler version is

gfortran --version
GNU Fortran (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609

推荐答案

这是一个微不足道的修改,它与gfortran配合得很好:

This is a slightly nontrivial modification, it works well with 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

这篇关于Fortran中的过程指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆