C interoperability

bind(C) procedures

The iso_c_binding module connects Fortran with the C language. A procedure marked with bind(C) uses the C calling convention and a fixed external name.

Start with one small interoperable function. Keep dummy arguments simple and interoperable, then test the Fortran side before wiring the C side.

module c_api use iso_c_binding implicit none contains function add_ints(a, b) bind(C, name="add_ints") result(c) implicit none integer(c_int), intent(in), value :: a integer(c_int), intent(in), value :: b integer(c_int) :: c c = a + b end function add_ints end module c_api

Matching C types

Fortran kinds with C names match common C types: c_int for C int and c_double for C double and c_char for C char.

Declare interoperable variables with those kinds and keep all other logic in normal Fortran kinds.

program c_types use iso_c_binding implicit none integer(c_int) :: n real(c_double) :: d n = 10 d = 1.5 print *, "n =", n, "d =", d end program c_types

C pointers round-trip

A C address travels as type(c_ptr). Fortran creates it with c_loc, tests it with c_associated, and converts it back with c_f_pointer.

The null address is c_null_ptr. Always test before converting, because converting a null address is an error.

program ptr_demo use iso_c_binding implicit none integer, target :: val type(c_ptr) :: cp integer, pointer :: fp val = 42 cp = c_loc(val) if (c_associated(cp)) then call c_f_pointer(cp, fp) print *, "fp =", fp end if end program ptr_demo

C strings

A C string is an array of c_char elements ended by a zero character. Fortran builds it element by element and adds achar(0) as the terminator.

Keep the buffer one element longer than the text so the terminator always fits.

program c_string use iso_c_binding implicit none character(kind=c_char) :: buf(4) buf(1) = "H" buf(2) = "i" buf(3) = "!" buf(4) = achar(0) print *, buf(1), buf(2), buf(3) end program c_string

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev