繁体   English   中英

如何在 Fortran 接口中使用用户定义类型

[英]How to use a user-defined-type in a Fortran interface

在一个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和子例程是同一个概念主题的一部分。

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

[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 编译器的优点,因此是普遍可用的(尽管公认导入是普遍实现的)

定义抽象数据类型/类时,IMPORT语句可能相关。 根据数据类型的不同,可能需要定义抽象接口,并且必须使用IMPORT语句来访问抽象接口块内的派生类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM