Fortran Expert · Lesson 1 · On the house

Interoperating with C

iso_c_binding kinds, bind(c) procedures, value arguments, and C strings. Lesson 1 is free — on the house.

Lessons · Fortran Expert · Lesson 1 of 10 · On the house

Interoperating with C

iso_c_binding kinds, bind(c) procedures, value arguments, and C strings.

Illustration for Fortran
Lesson 1 is on the house.

use iso_c_binding provides kinds that match C types: c_int, c_double, c_char, c_ptr, c_null_char. Use them for every argument that crosses the boundary.

bind(c, name='abs') gives a procedure C linkage. In an interface block it declares a C function you can call; on your own procedure it exports a C-callable symbol.

Fortran passes by reference; C usually passes by value. Mark scalar arguments value to match a C signature like int abs(int).

C strings are NUL-terminated arrays of character(kind=c_char); append c_null_char when passing a Fortran string to C.

Derived types declared bind(c) match C structs field for field, and c_loc/c_f_pointer convert between C pointers and Fortran pointers.

bind(c)

program cinterop
  use iso_c_binding, only: c_int, c_size_t, c_char, c_null_char
  implicit none
  interface
    function c_abs(x) bind(c, name='abs') result(r)
      import :: c_int
      integer(c_int), value :: x
      integer(c_int) :: r
    end function c_abs
    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 '(i0)', c_abs(-7_c_int)
  print '(i0)', c_strlen('fortran' // c_null_char)
end program cinterop
Match this when you type.

Quiz

Why mark x with value in c_abs?

Quiz

What must you append to a Fortran string passed to C?

Quiz

What does bind(c, name='abs') set?

Quiz

What does c_strlen('fortran' // c_null_char) print?

Check

Match the still for: Interoperating with C.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.