Interoperable derived types

A derived type can cross the boundary as well, provided both sides agree on the layout of the memory. Fortran says so with type, bind(c): the components are then laid out in the order they are declared, with no hidden descriptor, exactly as a C struct is. This lesson gives a point a C implementation and a Fortran implementation of the same record, and passes it back and forth.

TYPE, BIND(C)

type, bind(c) :: point with two real(c_double) components is a sixteen-byte record with the first double at offset zero and the second at offset eight. The attribute is a promise about the layout, and the compiler enforces the half of it it can: a component that C cannot represent is refused, which is the error of the last section.

The file types.f90:

module points use, intrinsic :: iso_c_binding implicit none type, bind(c) :: point real(c_double) :: x, y end type point interface subroutine move(p, dx, dy) bind(c, name="move") import :: point, c_double type(point), intent(inout) :: p real(c_double), value :: dx, dy end subroutine move function norm(p) bind(c, name="norm") result(r) import :: point, c_double type(point), intent(in) :: p real(c_double) :: r end function norm end interface end module points program typebridge use points implicit none type(point) :: p p = point(3.0_c_double, 4.0_c_double) print '(a,2f6.1)', 'start =', p%x, p%y print '(a,f10.3)', 'norm = ', norm(p) print '(a,i0)', 'storage_size = ', storage_size(p) call move(p, 2.0_c_double, 4.0_c_double) print '(a,2f6.1)', 'moved =', p%x, p%y print '(a,f10.3)', 'norm = ', norm(p) end program typebridge

The C struct

The C side is a struct of two doubles and two functions: one that moves it, through a pointer, and one that computes its length, through a pointer to const. Neither returns the struct by value, which keeps the calling convention to the easy case.

The file c_points.c:

#include <math.h> struct point { double x; double y; }; void move(struct point *p, double dx, double dy) { p->x += dx; p->y += dy; } double norm(const struct point *p) { return sqrt(p->x * p->x + p->y * p->y); }

The two calls

Build the two objects and link them, and the Fortran record goes to C as a pointer, comes back modified, and is measured by a second C function:

gcc -c -O2 c_points.c
gfortran -Wall -Wextra -std=f2018 -c types.f90
gfortran types.o c_points.o -o types
./types

start = 3.0 4.0
norm = 5.000
storage_size = 128
moved = 5.0 8.0
norm = 9.434

The point starts at three and four, whose length is five; C moves it by two and four to five and eight, whose length is 9.434. Both numbers came from the C function, and the Fortran side read the modified components afterwards, which is what an intent(inout) derived type means across the boundary.

The layout

storage_size(p) is 128 bits, so sixteen bytes: two doubles with no padding, which is what sizeof(struct point) gives in C. The component order is the declaration order in both languages, and the offsets follow from the sizes, so a struct of a char and a double would have padding that both compilers add the same way.

The promise does not extend to a component that is itself a derived type unless that one is also bind(c), and it does not extend to an array of a non-interoperable type. A nested record is fine when every level says bind(c), and the storage size check at each level is the cheapest test that the two sides still agree.

Through a c_ptr

Not every C struct has a Fortran declaration. A library that returns an opaque handle gives the Fortran side a type(c_ptr), which it passes back to the library and never inspects. To read a struct the program does know, c_f_pointer(p, fp) turns the handle into a Fortran pointer of the bind(c) type, and from there the components are ordinary members.

That is the same pair as lesson 104, one level up: c_loc out, c_f_pointer back, and the shape or the type supplied by the caller because the pointer carries neither. A program that gets the type wrong here reads the right bytes as the wrong record, and the compiler cannot help.

An allocatable component

A bind(c) type is a C struct, and a C struct has no descriptor for an allocatable:

program badtype use, intrinsic :: iso_c_binding implicit none type, bind(c) :: bad real(c_double), allocatable :: x end type bad type(bad) :: b allocate(b%x) b%x = 1.0_c_double print *, b%x end program badtype

gfortran -Wall -Wextra -std=f2018 badtype.f90 -o badtype

badtype.f90:6:36:

5 | type, bind(c) :: bad
| 2
6 | real(c_double), allocatable :: x
| 1
Error: Component 'x' at (1) cannot have the ALLOCATABLE attribute because it is a member of the BIND(C) derived type 'bad' at (2)

The message points at both lines, the component and the type, because the reason is the combination. A pointer component is allowed, since a C struct can hold a pointer, and an allocatable is not, since it needs a descriptor that C has never heard of. A record with variable-size data becomes a record of a pointer and a length in C.

Rules for a shared type

Give the type bind(c) and every component an interoperable type and kind. Keep the components in the same order on both sides, and check the size once with storage_size. Pass the record by reference, which is the default, and avoid returning it by value unless the platform's ABI is known to agree. And write the C struct in one header that both the C file and the documentation use.

The last lesson of this part is about the tools that automate the interface, and about the one that is missing from this image. The mechanism on this page is what all of them generate: a type with a known layout, a set of procedures with bind(c), and a description of both for the other language.

Exercises

  1. Add a third component integer(c_int) :: tag to both sides and print storage_size. What is the size now, and where is the padding?
  2. Add a C function that returns the struct by value and declare it in Fortran. Does it work on this machine? Why is that not a portable answer?
  3. Declare the C pointer of move as type(point), pointer instead of intent(inout). Which form does a C pointer match, and what would value mean there?
  4. Use c_f_pointer to turn the address from c_loc(p) back into a type(point) pointer and print its components. Which type has to be given to c_f_pointer?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does type, bind(c) promise?

    Answer

    The components are laid out as a C struct with the same members

    It is a layout promise the compiler enforces where it can.

  2. How does a Fortran record reach a C function that takes a pointer to it?

    Answer

    As a dummy without VALUE, which passes the address

    Fortran passes by reference by default.

  3. What does STORAGE_SIZE of the point with two c_double components give?

    Answer

    128 bits

    Two eight-byte doubles.

  4. What does this program print? program p use, intrinsic :: iso_c_binding implicit none type, bind(c) :: pair integer(c_int) :: a, b end type pair type(pair) :: v v = pair(2, 3) print *, v%a + v%b end program p

    Answer

    5

    Two plus three inside a struct that C could read.

  5. Which component may a bind(c) type not have?

    Answer

    An allocatable component

    C has no descriptor for an allocatable.

  6. What would a record with variable-size data look like in C?

    Answer

    A pointer and a length

    The Fortran side then holds a c_ptr and a size.

  7. What does c_f_pointer need besides the handle?

    Answer

    The type and shape of what it points at

    The pointer carries neither.

  8. Why avoid returning a struct by value from C to Fortran?

    Answer

    The ABI for struct return varies and is not portable across platforms

    It may work here and fail elsewhere.

  9. How is the size checked against C?

    Answer

    STORAGE_SIZE in Fortran against sizeof in C

    The cheapest test that the two sides still agree.

  10. What does a nested bind(c) type need for its layout to cross?

    Answer

    Every level declared bind(c)

    Each level is a layout promise.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev