Passing a FORTRAN object to C and vice versa

我是研究僧i 提交于 2019-12-08 05:34:08

问题


I have my Fortran object i.e.

this%object%a

this%object%b

this%object%c

I want to pass it to a code written in C, I am predominately a FORTRAN programmer and I have had very little exposure to C. I am using iso_c_binding to pass integers and arrays but now I need to pass objects.

I define the object in the following way

    TYPE object

         INTEGER                                  :: a

         INTEGER                                  :: b

         INTEGER                                  :: c

    END TYPE object

回答1:


You can make interoperable types:

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

There are restrictions in the standard on the object. For example, it cannot contain allocatable or pointer components.

When you pass it to an interoperable procedure:

void sub(c_object* x){}

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

call sub(o)

it is interoperable with a C struct

typedef struct {
  int a;
  int b;
  int c;
} c_object;

You can also pass non-interoperable types to C, but you have to use pointers:

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

call sub2(loc(o))


来源:https://stackoverflow.com/questions/26606958/passing-a-fortran-object-to-c-and-vice-versa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!