【问题标题】:Porting recursive C struct to Fortran将递归 C 结构移植到 Fortran
【发布时间】:2013-03-18 18:40:00
【问题描述】:

在 Fortran 中定义这个递归 C 结构的正确方法是什么?

struct OPTION {
        char option;
        char *arg;
        struct OPTION *next;
        struct OPTION *previous;
};

我已经编写了这个 Fortran 代码:

module resources
use iso_c_binding
implicit none
   type :: OPTION
      character(c_char) :: option
      character(c_char) :: arg
      type(OPTION), pointer :: next
      type(OPTION), pointer :: previous
   end type OPTION
end module resources

这可以编译,但我认为这是错误的,因为缺少类型定义中的bind(c)。如果我尝试将type, bind(c) :: OPTION gfortran 归咎于Error: Component 'next' at (1) cannot have the POINTER attribute because it is a member of the BIND(C) derived type 'option' at (2)

如果我保留type, bind(c) :: OPTION 并删除POINTER 属性,我会得到Error: Component at (1) must have the POINTER attribute

【问题讨论】:

    标签: c struct interop fortran fortran-iso-c-binding


    【解决方案1】:

    试试:

       type, bind(c) :: OPTION
          character(c_char) :: option
          character(c_char) :: arg
          type(c_ptr) :: next
          type(c_ptr) :: previous
       end type OPTION
    

    Fortran 中的 C 指针并不真正被视为指针,而是被视为完全独立的类型。您必须通过 C_F_POINTER 将它们转换为 Fortran 指针才能充分利用它们。

    【讨论】:

      【解决方案2】:

      您可以通过 type(c_ptr) 类型使用 C 类型指针:

      module resources
        use iso_c_binding
        implicit none
        type, bind(c) :: OPTION
          character(c_char) :: option
          character(c_char) :: arg
          type(c_ptr) :: next
          type(c_ptr) :: previous
        end type OPTION
      end module resources
      

      【讨论】:

      • nextand previousare type OPTION 不是指针,这是我的问题。
      • 使用type(c_ptr),您可以映射所有独立于其类型的C 指针。但是,正如none_00's post 所述,您必须通过C_F_POINTER 转换它们才能访问它们的字段。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多