首页 文章

接口C函数与Fortran中的结构[重复]

提问于
浏览
5

这个问题在这里已有答案:

我想将C函数与Fortran中的相应结构相链接

struct ovf_file {
    bool found;
    bool is_ovf;
    int n_segments;
    struct ovf_file_handle *_file_handle;
};
DLLEXPORT struct ovf_file * ovf_open(const char *filename);

这是我尝试这样做的:

module ovf
    use, intrinsic :: iso_c_binding
    implicit none

    type, bind(c) :: ovf_file
      logical(c_bool)   :: found
      logical(c_bool)   :: is_ovf
      integer(c_int)    :: n_segments
      type(c_ptr)       :: file_handle
    end type ovf_file
end module ovf

program main
    use ovf
    use, intrinsic :: iso_c_binding
    implicit none
    type(ovf_file)               :: file_handle

    interface
      function ovf_open(filename) bind ( C, name = "ovf_open" ) result(handle)
        character(len=1, kind=c_char), intent(in) :: filename
        type(ovf_file)                            :: handle
      end function ovf_open
    end interface

    file_handle = ovf_open("testfile.ovf"//C_NULL_CHAR)
end program main

这是我通常做的接口C,但gfortran(或ifort)将不会编译此代码(我甚至没有尝试将其链接到C二进制文件) . 这是编译器输出:

gfortran -c src/fortran_wrapper.f90                                                                                                                                                               [±master ●●]
src/fortran_wrapper.f90:22:30:

         character(len=1, kind=c_char), intent(in) :: filename
                              1
Error: Parameter ‘c_char’ at (1) has not been declared or is a variable, which does not reduce to a constant expression
src/fortran_wrapper.f90:23:22:

         type(ovf_file)                            :: handle
                      1
Error: Derived type ‘ovf_file’ at (1) is being used before it is defined
src/fortran_wrapper.f90:30:12:

     ulala = ovf_open("testfile.ovf"//C_NULL_CHAR)
            1
Error: Type mismatch in argument ‘filename’ at (1); passed CHARACTER(1) to REAL(4)
src/fortran_wrapper.f90:30:12:

     ulala = ovf_open("testfile.ovf"//C_NULL_CHAR)
            1
Error: Can't convert REAL(4) to TYPE(ovf_file) at (1)

为什么它知道模块中的C类型,而不是程序,即使我有相同的use-clause?即使我包含模块,为什么不能找到类型?

我只能找到非常简单的C互操作性用例 . 没有解释结构或C字符串 . 我该怎么做呢?

1 回答

  • 2

    你必须在界面中重复“使用iso_c_binding”(就在函数ovf ...之后)

    或者您可以导入C符号 . 这很遗憾,但接口不知道使用过的模块 .

相关问题