TExcelTAD
Home › Fortran › Fortran Interoperability with C

Fortran Interoperability with C

Since Fortran 2003, the language has a standard way to call C code and to be called from C: the intrinsic module iso_c_binding and the bind(c) attribute. This lets Fortran use system libraries, and it's how Python (via ctypes, Cython or f2py), Julia, R and C++ call Fortran libraries.

The building blocks

Feature Purpose
use, intrinsic :: iso_c_binding kind constants that match C types, plus helper procedures
integer(c_int), real(c_double), character(c_char) … variables with exactly the C layout
bind(c, name='func') gives a procedure C linkage and a fixed symbol name
value passes an argument by value, as C does by default
type(c_ptr), c_loc, c_f_pointer C pointers and conversion to Fortran pointers
c_null_char the '\0' string terminator

Matching kinds:

C type Fortran declaration
int integer(c_int)
long / int64_t integer(c_long) / integer(c_int64_t)
size_t integer(c_size_t)
float / double real(c_float) / real(c_double)
char character(kind=c_char)
T* an array or scalar argument (by reference), or type(c_ptr), value

Calling a C function from Fortran

The C library is always linked into a gfortran program, so we can call its functions directly. You write an interface that describes the C prototype in Fortran terms:

fortran · try it yourself
program call_libc
  use, intrinsic :: iso_c_binding, only: c_int, c_double, c_size_t, c_char, c_null_char
  implicit none

  interface
    ! double hypot(double x, double y);   from libm
    function c_hypot(x, y) bind(c, name='hypot') result(r)
      import :: c_double
      real(c_double), value :: x, y
      real(c_double) :: r
    end function c_hypot

    ! int abs(int n);
    function c_abs(n) bind(c, name='abs') result(r)
      import :: c_int
      integer(c_int), value :: n
      integer(c_int) :: r
    end function c_abs

    ! size_t strlen(const char *s);
    function c_strlen(s) bind(c, name='strlen') result(n)
      import :: c_char, c_size_t
      character(kind=c_char), intent(in) :: s(*)
      integer(c_size_t) :: n
    end function c_strlen
  end interface

  print '(a, f8.3)', 'hypot(3, 4) = ', c_hypot(3.0_c_double, 4.0_c_double)
  print '(a, i0)',   'abs(-42)    = ', c_abs(-42_c_int)
  print '(a, i0)',   'strlen      = ', c_strlen('interoperable' // c_null_char)
end program call_libc
hypot(3, 4) =    5.000
abs(-42)    = 42
strlen      = 13

Three important details:

  1. value: C passes scalars by value, Fortran by reference. Without value, C would receive a pointer and misread it.
  2. Strings: C strings end with a NUL byte, so append c_null_char. A C char * maps to a character array s(*) of kind c_char.
  3. name=: the exact, case-sensitive C symbol. Without it, the binding label is the lower-case Fortran name.

Callbacks: passing a Fortran function to C

The C standard library's qsort takes a comparison function pointer. A bind(c) Fortran function can be passed to it with c_funloc, and the array with c_loc:

fortran · try it yourself
module sorting
  use, intrinsic :: iso_c_binding
  implicit none

  interface
    ! void qsort(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *));
    subroutine qsort(base, n, size, compar) bind(c, name='qsort')
      import :: c_ptr, c_size_t, c_funptr
      type(c_ptr), value :: base
      integer(c_size_t), value :: n, size
      type(c_funptr), value :: compar
    end subroutine qsort
  end interface

contains

  ! called by C with pointers to two doubles
  integer(c_int) function compare_doubles(pa, pb) bind(c)
    type(c_ptr), value :: pa, pb
    real(c_double), pointer :: a, b
    call c_f_pointer(pa, a)               ! turn the C pointers into Fortran pointers
    call c_f_pointer(pb, b)
    if (a < b) then
      compare_doubles = -1
    else if (a > b) then
      compare_doubles = 1
    else
      compare_doubles = 0
    end if
  end function compare_doubles

end module sorting

program sort_with_c
  use sorting
  implicit none
  real(c_double), target :: values(7) = [3.5_c_double, -1.0_c_double, 8.25_c_double, &
                                         0.0_c_double, 2.0_c_double, -7.5_c_double, 4.0_c_double]

  call qsort(c_loc(values), size(values, kind=c_size_t), c_sizeof(values(1)), &
             c_funloc(compare_doubles))
  print '(*(f7.2))', values
end program sort_with_c
  -7.50  -1.00   0.00   2.00   3.50   4.00   8.25

c_loc(values) needs the target attribute, c_sizeof gives the element size in bytes (8), and c_f_pointer converts a C address back into a typed Fortran pointer.

Calling Fortran from C

The opposite direction works the same way. A bind(c) procedure in Fortran:

fortran
! file: stats.f90
module stats_c
  use, intrinsic :: iso_c_binding, only: c_int, c_double
  implicit none
contains
  function mean(x, n) bind(c, name='fortran_mean') result(m)
    integer(c_int), value :: n
    real(c_double), intent(in) :: x(n)
    real(c_double) :: m
    m = sum(x) / n
  end function mean
end module stats_c

is called from C with an ordinary prototype:

c
/* file: main.c */
#include <stdio.h>
double fortran_mean(const double *x, int n);

int main(void) {
    double data[] = {1.0, 2.0, 6.0};
    printf("%.3f\n", fortran_mean(data, 3));   /* prints 3.000 */
    return 0;
}
bash
gfortran -c stats.f90
gcc -c main.c
gfortran main.o stats.o -o app       # link with gfortran so the Fortran runtime is included

Things to watch

  • Array order: a Fortran a(m, n) is column-major; a C double a[m][n] is row-major. Passing a matrix between them transposes it unless you account for it.
  • Indexing: C starts at 0, Fortran (by default) at 1. The memory is the same; only the index arithmetic differs.
  • Logical values: use logical(c_bool) for C's _Bool; a default Fortran logical is not guaranteed to match.
  • Assumed-shape arrays and allocatables can also be passed to C since Fortran 2018 through C descriptors (ISO_Fortran_binding.h), but explicit-size arrays plus a length argument remain the simplest, most portable interface.

Test yourself

Why do scalar arguments of C functions usually need the value attribute?

  1. For speed only
  2. C passes scalars by value, while Fortran passes by reference by default
  3. To make them constant
  4. Because C has no integers

Which Fortran type matches a C double?

  1. real
  2. real(c_double)
  3. double precision(c)
  4. real(8) always

What must be appended to a Fortran string passed to a C function expecting const char *?

  1. Nothing
  2. A blank
  3. c_null_char
  4. new_line('a')