Matty
Matty

Reputation: 33

Passing a FORTRAN object to C and vice versa

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

Upvotes: 2

Views: 968

Answers (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))

Upvotes: 6

Related Questions