c - 通过C函数定义的Fortran派生类型构造函数(二)

标签 c binding fortran

以下问题 Fortran derived type constructor defined though C function ,我想到了这个非工作示例,使用 gfortran 4.9:

module my_module
  use iso_c_binding
  type, bind(c) :: my_double
     real(c_double) :: x
     real(c_double) :: y
  end type my_double
  interface my_double
      procedure my_module_fortran_new_my_double
  end interface
  interface
     type(my_double) function my_module_fortran_new_my_double (v) bind ( c )
       use iso_c_binding
       import :: my_double
       real (c_double), intent(in) :: v
     end function my_module_fortran_new_my_double
  end interface
end module my_module

program main
  use my_module
  type(my_double) x
  x = my_double(12)
end program main

继上一个问题Fortran derived type constructor defined though C function ,模块定义工作正常。但是,我的编译器无法识别定义的构造函数。

这是编译器的输出:

$ gfortran -std=f2008 test.f90 -o test.o -c
test.f90:22.6:

  x = my_double(12)
      1
Error: No initializer for component 'y' given in the structure constructor at (1)!

这似乎没有考虑我使用的定义构造函数。有人可以帮助我理解我做错了什么(再次)吗?

最佳答案

对于特定的构造函数来匹配

my_double(12)

必须有一个有接口(interface)的程序

type(my_double) function something(i, ...) ...
   integer ... :: i
   ..., optional, ... :: ...
end function

因为给定的单个组件源是 integer 类型。

所提供的唯一非默认特定构造函数是具有一个 real(c_double) 类型的非可选组件源的构造函数。

要解决,两种方法:

  • 添加一个采用默认整数的特定过程;或
  • 为非默认构造函数指定一个适当的参数。

对于后者:

x = my_double(12._c_double)   ! c_double from intrinsic iso_c_binding

值得注意的是为什么会出现这个问题。你可以愉快地尝试

x = my_double(12,13)  ! Using the normal constructor
x = my_double(12)     ! Using the normal constructor if default
                      ! initialization applies for component y

与隐式构造函数一样,存在源术语(遵循内在赋值规则)到组件本身的类型/参数的转换。这种转换不适用于解析泛型的情况。

关于c - 通过C函数定义的Fortran派生类型构造函数(二),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41278744/

相关文章:

c - 获取文件中元素的数量

ruby - 如何在 ruby​​ 中创建具有给定绑定(bind)的 block ?

c++ - 将 LuaBridge 与指向内置类型的指针一起使用

pointers - 如何判断Fortran过程指针是否与特定子程序关联

arrays - FORTRAN 中的数组声明,适合初学者

c - 在确定字符数的同时打印数组

c++ - 表示命令包格式的数据结构

string - 在 Fortran 中获取可变长度字符串列表的更好方法

sql - Pro*C Oracle——循环获取 sql

wpf - RelativeSource FindAncestor 问题