Examples: iso_c_binding calling Fortran from C

I’ve seen only examples of iso_c_binding being used to call a C routine from Fortran. What are some detailed/comprehensive simple examples of calling Fortran functions and subroutines.

How complex can these iso_c_binding C to Fortran (and vice versa) interfaces be?

Thank you

1 Like

You can do some pretty fancy things these days on either side of the language barrier. And if you’ve watched my video on it, you have seen C calling Fortran.

1 Like

The C interoperability features have several parts. The module ISO_C_Binding is just some declarations of constants, types and functions that are useful in Fortran code for interoperating with C. The BIND(C) “language binding spec” is another important part.

Fortran 2018 greatly extended C interoperability, by allowing you to pass a wider variety of things between Fortran and C (in both directions). This is enabled by a C include file called ISO_Fortran_binding.h, which declares macros and functions for manipulating what Fortran calls “C descriptors”. With these, C code can accept and pass allocatable and pointer variables, arrays with bounds, character strings with length, and more.


My advice is to don’t waste your time looking for detailed documentation because it probably doesn’t exist. Your best path is to write short test programs that concentrate on the interface (ie arguments) and making sure they are passed correctly and consistently. After that concentrate on memory management and who needs to allocate/free what and when. The rule of thumb is anything allocated in Fortran needs to be deallocated in Fortran. Anything malloced in C/C++ needs to be freed by C/C++.

Sort of relevant. Here are examples for how to call fortran from python via iso_c_binding and cython. The process involves

  1. Make a C interface for the Fortran
  2. Call the C functions from Cython

They can get very complicated. As long as your are creative, any Fortran code can be called from C (or from Python).

1 Like

There’s some very important nuance missing it your summation here. Anything more than the specific example I was working on in terms of passing strings between the languages is like asking to please find and report all the bugs in the various compilers to you. If you encounter a case a compiler isn’t handling correctly, you report the bug to that compiler and find a workaround specific to that case. I can’t predict the future, sorry to say.

I gave a worked example of the F2018 C interoperability features in a presentation I gave last year, Modern Fortran. It starts around slide 35.