4

在 Fortran 2003 模块中,我定义了一个名为的类型t_savepoint,稍后,我想为一个名为 的子例程定义一个接口,该子例程fs_initializesavepoint将一个类型的对象t_savepoint作为唯一参数。

这是整个模块的代码:

module m_serialization

    implicit none

    type :: t_savepoint
        integer :: savepoint_index
        real    :: savepoint_value
    end type t_savepoint

    interface

        subroutine fs_initializesavepoint(savepoint)
            type(t_savepoint) :: savepoint
        end subroutine fs_initializesavepoint


    end interface

end module m_serialization

我想要这样一个接口的原因是稍后我会让这个 fortran 模块与 C 互操作。

如果我尝试编译它(gfortran-4.7.0),我会收到以下错误消息:

            type(t_savepoint) :: savepoint
                                          1
Error: The type of 'savepoint' at (1) has not been declared within the interface

如果我在子例程中移动类型的定义,错误就会消失;但是如果我想在许多子程序中使用相同的类型,我应该在所有子程序中重复定义吗?

先感谢您。

编辑:一种解决方案是将类型的定义移到另一个模块上,然后use在每个子例程中移到它。但是我不太喜欢这个解决方案,因为类型t_savepoint和子例程是同一个概念主题的一部分。

4

1 回答 1

8

在接口块中正确或错误地,您无法通过主机关联访问环境。要解决此问题,您需要显式导入数据类型:

[luser@cromer stackoverflow]$ cat type.f90
module m_serialization

  implicit none

  type :: t_savepoint
     integer :: savepoint_index
     real    :: savepoint_value
  end type t_savepoint

  interface

     subroutine fs_initializesavepoint(savepoint)
       Import :: t_savepoint
       type(t_savepoint) :: savepoint
     end subroutine fs_initializesavepoint


  end interface

end module m_serialization
[luser@cromer stackoverflow]$ gfortran -c type.f90

这是f2003。

但是,我怀疑您提出的方式表明您不会以最好的方式对其进行编码。更好的是将例程本身放在模块中。然后你根本不需要介意界面:

module m_serialization

  implicit none

  type :: t_savepoint
     integer :: savepoint_index
     real    :: savepoint_value
  end type t_savepoint

Contains

  Subroutine fs_initializesavepoint(savepoint)

    type(t_savepoint) :: savepoint 

    Write( *, * ) savepoint%savepoint_index, savepoint%savepoint_value

  End Subroutine fs_initializesavepoint

end module m_serialization
[luser@cromer stackoverflow]$ gfortran -c type.f90

鉴于模块实际上是为处理连接实体而设计的,这确实是在 Fortran 中执行此操作的方式。它还具有只需要 f95 编译器的优点,因此是普遍可用的(尽管公认导入是通常实现的)

于 2012-12-13T10:45:13.230 回答