Reading and writing structures in C

c, fortran

Solution

Yes, Fortran 2003 introduced the `bind(C)` specifier which tells the compiler to do exactly the same as the companion C compiler does

type, bind(C) :: a
  components
end type

Additionally, the `iso_c_binding` module (a subpart of the whole Fortran 2003 C interoperability) defines constants which help you connect the C and Fortran intrinsic types:

use intrinsic :: iso_c_binding, only: c_short, c_int

type, bind(C) :: a
  integer(c_short) :: x
  integer(c_int) :: y
end type

Such type is said to be interoperable with your C struct.

The C interoperability is very widely supported in compilers. It is very difficult to find a compiler which does not support this feature and is still supported by its vendor.

Stay away from `sequence` when mixing C and Fortran. Sequence types cannot be made interoperable according to the standard.

Problem

I know that structs in C may not be laid out memory as they are in the code. For example: ``` struct a { short x; int y; }; ``` assuming 2 byte shorts and 4 byte ints, may actually take 8 bytes in memory as the compiler wants to align the members on 4 byte boundaries ... so there is 2 bytes of slack between x and y. This makes reading and writing structs unportable across language, compiler, and hardware. The only way to read and write them is member by member. Yes, Endianness is also an issue here and swapping must be done at the member level but lets assume this is not an issue. Fortran has a 'sequence' specifier for derived types (structures) that tells the compiler to lay out the members in memory as they are given. This allows portable reading and writing of derived types. My question is: Is there any way to do a similar thing in C in a portable (and maintainable) way?

Original source