Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Parallel and Scientific Computing

Fortran and C Interoperability with iso_c_binding

Call C from Fortran and Fortran from C with iso_c_binding: bind(c), c_int and c_double kinds, value arguments, C strings, arrays, structs and callbacks.

Fortran's strength is numerical array code, but the software world is full of C libraries: operating system calls, graphics, compression, networking. And your Fortran solver may need to be called from C, C++ or Python. Since Fortran 2003 the language has a standard mechanism for this: the intrinsic module iso_c_binding and the bind(c) attribute. No vendor extensions or compiler-specific name tricks are needed.

You cannot link Fortran with C in the browser. The Fortran listings are read-only. The C side of one example is runnable on the C runner, and a Python stand-in shows the calling convention.

The idea

Two languages can call each other safely if they agree on three things: the names of procedures in the object file, the data representation of arguments, and how arguments are passed. iso_c_binding supplies all three:

  • kind constants whose representation matches C types,
  • bind(c) to give a procedure or type C naming and layout,
  • value to pass by value, as C does by default.

Kind constants

C type Fortran kind
int integer(c_int)
long integer(c_long)
long long / int64_t integer(c_long_long) / integer(c_int64_t)
float real(c_float)
double real(c_double)
char character(kind=c_char)
_Bool logical(c_bool)
void * type(c_ptr)
function pointer type(c_funptr)

Use these instead of guessing that integer is 4 bytes, even though it usually is.

Calling C from Fortran

Suppose C provides this function:

C
double scale_sum(const double *x, int n, double factor);

Describe it to Fortran with an interface block:

FORTRAN
module c_api
  use, intrinsic :: iso_c_binding
  implicit none

  interface
    function scale_sum(x, n, factor) bind(c, name="scale_sum") result(r)
      import :: c_double, c_int
      real(c_double), intent(in) :: x(*)
      integer(c_int), value :: n
      real(c_double), value :: factor
      real(c_double) :: r
    end function scale_sum
  end interface

end module c_api

Pieces to note:

  • bind(c, name="scale_sum") sets the linker symbol. Without name= the symbol is the lower-case Fortran name.
  • value on n and factor matches C's pass-by-value. Without it, Fortran would pass addresses, and C would read garbage.
  • x(*) is an assumed-size array: Fortran passes the address of the first element, matching const double *. Fortran arrays are contiguous and column-major, so a one-dimensional array maps cleanly to a C array.
  • import brings names from the host into the interface body.

The call looks like any Fortran call:

FORTRAN
program use_c
  use c_api
  use, intrinsic :: iso_c_binding, only: c_double, c_int
  implicit none
  real(c_double) :: v(4) = [1d0, 2d0, 3d0, 4d0]
  print *, scale_sum(v, 4_c_int, 2.5_c_double)
end program use_c

and links with the C object file: gcc -c scale.c && gfortran use_c.f90 scale.o -o use_c.

Here is the C side, runnable on the C runner with a small main that makes the same call (the answer is (1+2+3+4) * 2.5 = 25):

C The C function that Fortran would call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Calling Fortran from C

Write the Fortran procedure with bind(c):

FORTRAN
subroutine axpy(n, a, x, y) bind(c, name="axpy")
  use, intrinsic :: iso_c_binding
  integer(c_int), value :: n
  real(c_double), value :: a
  real(c_double), intent(in)    :: x(n)
  real(c_double), intent(inout) :: y(n)
  y = a * x + y
end subroutine axpy

and declare it in C:

C
void axpy(int n, double a, const double *x, double *y);

C passes x and y as pointers, which Fortran receives as arrays because they are not value. Note x(n) uses the earlier argument n for its size, which is legal because n is a dummy argument too.

Python Stand-in: by-value versus by-reference

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Strings

C strings are char * ending in a zero byte. Fortran strings are fixed-length and blank-padded. Convert at the boundary:

FORTRAN
character(len=:, kind=c_char), allocatable :: s    ! allocatable string
character(kind=c_char, len=6) :: hello = "Hello" // c_null_char

c_null_char supplies the terminating zero. When C passes a string in, declare the dummy character(kind=c_char), intent(in) :: s(*) and scan up to c_null_char. Memory ownership is the usual C hazard: know who allocates and who frees.

Structs and derived types

A derived type with bind(c) has the same layout as a C struct:

FORTRAN
type, bind(c) :: point
  real(c_double) :: x, y
  integer(c_int) :: id
end type point

matches

C
struct point { double x, y; int id; };

Only interoperable components are allowed: no allocatable, pointer or type-bound members.

Pointers, callbacks and C memory

  • type(c_ptr) holds a C pointer. c_loc(x) takes the address of a Fortran target, and c_f_pointer(cptr, fptr, [n]) turns a C pointer into a Fortran array pointer of size n.
  • type(c_funptr) holds a function pointer, and c_f_procpointer converts it. Passing a Fortran callback to C needs the procedure itself to be bind(c).
  • Memory from malloc in C must be freed by C, not with deallocate.
FORTRAN
type(c_ptr) :: cp
real(c_double), pointer :: arr(:)
! cp = c_malloc(...)          (via an interface to malloc)
call c_f_pointer(cp, arr, [100])

Multi-dimensional arrays: mind the layout

Fortran stores a(i, j) column-major; C stores a[i][j] row-major. A 3-by-4 Fortran array a(3,4) therefore looks like a[4][3] to C, transposed. Swap the indices at the boundary, or document it loudly. This single mismatch causes a large share of interop bugs.

flowchart LR
    A["Fortran caller"] -->|"bind(c), value,<br/>c_int, c_double"| B["C library"]
    C["C caller"] -->|"extern declaration"| D["Fortran bind(c) procedure"]
    E["Python / C++"] -->|"ctypes / extern C"| D

bind(c) makes the same object file callable from both directions.

Calling Fortran from Python

Because a bind(c) procedure looks like a C function, Python's ctypes (or cffi) can call it from a shared library built with gfortran -shared -fPIC axpy.f90 -o libaxpy.so. F2PY from NumPy also wraps Fortran automatically. This is why many scientific Python packages (SciPy, for example) have Fortran kernels inside.

Common mistakes

  • Forgetting value for scalars C passes by value.
  • Using plain integer/real instead of c_int/c_double.
  • Leaving out the c_null_char in a string.
  • Mixing up row-major and column-major layouts.
  • Putting bind(c) on a type with allocatable components.
  • Name mangling surprises: always state name= explicitly.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the value attribute do for a dummy argument?

    value passes a copy, which is what C does for scalars by default.
  2. 2. Which Fortran type matches a C double?

    iso_c_binding provides c_double so the representation matches C's double.
  3. 3. What does bind(c, name='f') set?

    It gives the procedure C linkage with the given external name.
  4. 4. A C string must end with what?

    C strings are zero-terminated, while Fortran strings are blank-padded, so add c_null_char at the boundary.

Summary

  • iso_c_binding plus bind(c) standardizes calls in both directions.
  • Use c_int, c_double, c_ptr and friends; pass C scalars with value.
  • bind(c) types match C structs; strings need c_null_char; remember column-major versus row-major.
  • c_loc and c_f_pointer convert between Fortran and C pointers.
  • The same mechanism lets Python (ctypes) and C++ call Fortran kernels.

Next: Project: a statistics module