将FORTRAN对象传递给C,反之亦然

Mat*_*tty 1 c fortran object argument-passing fortran-iso-c-binding

我有我的Fortran对象,即

this%object%a

this%object%b

this%object%c
Run Code Online (Sandbox Code Playgroud)

我想将其传递给用C编写的代码,我主要是FORTRAN程序员,对C的接触很少。我iso_c_binding过去一直在传递整数和数组,但现在我需要传递对象。

我通过以下方式定义对象

    TYPE object

         INTEGER                                  :: a

         INTEGER                                  :: b

         INTEGER                                  :: c

    END TYPE object
Run Code Online (Sandbox Code Playgroud)

Vla*_*r F 5

您可以创建可互操作的类型:

use iso_c_binding

TYPE, BIND(C) :: object

     INTEGER(c_int)                                :: a

     INTEGER(c_int)                                :: b

     INTEGER(c_int)                                :: c

END TYPE object

type(object) :: o
Run Code Online (Sandbox Code Playgroud)

该对象的标准中有限制。例如,它不能包含可分配组件或指针组件。

当您将其传递给可互操作的过程时:

void sub(c_object* x){}

subroutine sub(x) bind(C,name="sub")
  type(object), intent(inout) :: x
end subroutine

call sub(o)
Run Code Online (Sandbox Code Playgroud)

它可以与C结构互操作

typedef struct {
  int a;
  int b;
  int c;
} c_object;
Run Code Online (Sandbox Code Playgroud)

您还可以将不可互操作的类型传递给C,但是必须使用指针:

subroutine sub2(x) bind(C,name="sub")
  type(c_ptr), value :: x
end subroutine

call sub2(loc(o))
Run Code Online (Sandbox Code Playgroud)