iso_c_binding: kinds and types

Fortran and C can call each other, and the price of the bridge is a module of names that both sides agree on. iso_c_binding defines them: kinds that mean the same thing in both languages, pointer types that pass through a C signature, and the conversion routines between what Fortran holds and what C expects. This lesson declares one of each, prints the sizes that make the promise checkable, and follows a Fortran array out to a C pointer and back.

iso_c_binding

The module is intrinsic, so use, intrinsic :: iso_c_binding needs no library and no file. It holds no procedures that do anything at run time except the four conversion ones; everything else is a named constant that the compiler knows. The promise is the same from both directions: a Fortran integer(c_int) has the representation a C int has, on every platform where the two compilers agree about anything.

The file kinds.f90:

program ckinds use, intrinsic :: iso_c_binding implicit none integer(c_int) :: i real(c_double) :: d character(kind=c_char, len=8) :: s type(c_ptr) :: p real(c_double), target :: a(3) real(c_double), pointer :: pa(:) integer :: j print '(a,i0)', 'c_int kind = ', c_int print '(a,i0)', 'c_double kind = ', c_double print '(a,i0)', 'c_char kind = ', c_char print '(a,i0)', 'default integer kind = ', kind(j) print '(a,i0)', 'size of a c_int = ', storage_size(i) / 8 print '(a,i0)', 'size of a c_double = ', storage_size(d) / 8 print '(a,i0)', 'size of a default int= ', storage_size(j) / 8 p = c_null_ptr print '(a,l1)', 'p before c_loc = ', c_associated(p) a = [1.5_c_double, 2.5_c_double, 3.5_c_double] p = c_loc(a(1)) print '(a,l1)', 'p after c_loc = ', c_associated(p) call c_f_pointer(p, pa, [3]) print '(a,3f6.1)', 'through c_f_pointer =', pa s = 'c_char' print '(a,a,a,i0)', 'c_char string = [', s(1:6), '] len = ', len(s) end program ckinds

gfortran -Wall -Wextra -std=f2018 kinds.f90 -o kinds
./kinds

c_int kind = 4
c_double kind = 8
c_char kind = 1
default integer kind = 4
size of a c_int = 4
size of a c_double = 8
size of a default int= 4
p before c_loc = F
p after c_loc = T
through c_f_pointer = 1.5 2.5 3.5
c_char string = [c_char] len = 8

The kinds it names

c_int is four in this build, which is the same as the default integer kind, and that coincidence is exactly why the module exists: the default kind is allowed to be anything, and a program that passes it to C is right only on the platforms where it happens to match. c_double is eight and c_char is one, and every one of them is a value the compiler chose so that the C declaration on the other side is the same type.

Beyond the three used here the module names c_float, c_long, c_long_long, c_int8_t and the rest of the fixed-width family, and c_bool for C's _Bool. It also names the two pointer types, c_ptr and c_funptr, which are the only kinds of pointer a C signature can carry.

Sizes that match C

storage_size returns bits, and the division by eight in the program is the conversion to bytes. Four, eight and four are what a C compiler in the same container would report for int, double and int; the page uses the Fortran enquiry because it needs no second compiler to be true, and the next lesson checks the C side by calling it.

A size is not the whole promise: c_double also says the alignment and the IEEE format, and c_char says that a character has one byte. The standard leaves the exact list to the implementation and requires the two compilers of one platform to agree, which is what makes the module portable and what makes it useless across a network with a different platform at the far end.

C_PTR, C_LOC and C_F_POINTER

type(c_ptr) is an opaque handle: a Fortran program can hold it, compare it with c_null_ptr using c_associated, and pass it to C, and it cannot dereference it. To get an address into one, c_loc(a(1)) takes a variable that is a target or a pointer; to get data back out, c_f_pointer(p, pa, [3]) associates a Fortran pointer with the memory and the shape it is told.

The round trip in the program is what a C function that returns a buffer looks like from Fortran: the C side allocates, Fortran receives a c_ptr, and c_f_pointer turns it into an array with a shape the Fortran side decided. The shape is the caller's promise, not the pointer's: nothing in a c_ptr says how long the memory is.

Characters and C strings

A Fortran character is a fixed length with no terminator; a C string is a pointer to bytes with a zero at the end. c_null_char is that zero, and a program that passes a string to C appends it, as the assignment in the program does. The Fortran length stays eight because the declaration said eight, so the string carries the terminator and the padding, and the C side stops at the first zero.

Coming the other way, a C function fills a character(kind=c_char) array and the Fortran side has to find the terminator itself with index(s, c_null_char). That is one line, and it is the one line most interop bugs are missing: trim does not stop at a zero, it stops at a blank.

C_LOC without TARGET

c_loc takes the address of something, so the something has to be addressable in the language's terms:

program badloc use, intrinsic :: iso_c_binding implicit none real(c_double) :: a(3) type(c_ptr) :: p a = 1.0_c_double p = c_loc(a(1)) print *, c_associated(p) end program badloc

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

badloc.f90:8:12:

8 | p = c_loc(a(1))
| 1
Error: Argument X at (1) to C_LOC shall have either the POINTER or the TARGET attribute

The dummy is called X in the standard, hence the capital in the message. The fix is one word in the declaration, real(c_double), target :: a(3), and the same word is needed on every variable whose address crosses the boundary.

Rules for the boundary

Use the kinds of iso_c_binding for everything that crosses, and never a default kind. Give target to every variable whose address is taken, and pass a shape alongside a pointer because the pointer does not carry one. Append c_null_char to every string that goes to C and look for it in every string that comes back. And keep the two declarations of one interface in one place, which is the subject of the next two lessons.

One more rule is easy to forget because the compiler cannot check it: the C function must not keep a pointer to a Fortran variable that will go out of scope. A target attribute says the address may be taken, not that the variable lives for ever, and a C library that stores the pointer and writes to it later is a dangling reference on the Fortran side.

Exercises

  1. Print storage_size of integer(c_int64_t) and of real(c_float). Which C types are they?
  2. Make a a pointer instead of a target and call c_loc(a). Does it compile, and what has to be allocated first?
  3. Find the terminator of s with index(s, c_null_char) in the program of the first section. What does it return for the string as assigned?
  4. Declare type(c_funptr) :: fp and print c_associated(fp) before it is set. What does a function pointer hold when it is null?

Questions

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

  1. What does iso_c_binding provide?

    Answer

    Kinds and types whose representation matches C, and the conversion routines

    It is the interface module of the standard.

  2. Why not pass a default integer to a C int?

    Answer

    The default kind is implementation defined; c_int is not

    The module exists to remove the coincidence.

  3. What does this program print if both kinds are four? program p use, intrinsic :: iso_c_binding implicit none integer(c_int) :: i integer :: j print *, storage_size(i) / 8, storage_size(j) / 8 end program p

    Answer

    4 4

    Both are four bytes in this build.

  4. What can a Fortran program do with a type(c_ptr)?

    Answer

    Hold it, compare it with C_NULL_PTR and pass it, but not dereference it

    C_F_POINTER is the only way back to data.

  5. What does c_f_pointer(p, pa, [3]) need that the pointer does not carry?

    Answer

    The shape

    A C pointer has no length.

  6. Why append c_null_char to a string passed to C?

    Answer

    A C string ends at a zero byte and a Fortran character has no terminator

    C reads until the terminator.

  7. What does trim do with a C string that came back?

    Answer

    It stops at a blank, not at the zero byte, so the terminator stays

    index(s, c_null_char) is the correct search.

  8. What does gfortran report for c_loc of a variable without TARGET?

    Answer

    Error: argument X to C_LOC shall have either the POINTER or the TARGET attribute

    The address of a non-target may not be taken.

  9. What does TARGET promise?

    Answer

    That the address may be taken, not that the variable lives for ever

    A C library that stores the pointer can still dangle.

  10. Which type carries a C function pointer?

    Answer

    type(c_funptr)

    The module names both pointer types.

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