Lead Image © Kheng Ho Toh, , 123RF.com

Lead Image © Kheng Ho Toh, , 123RF.com

Accessing Fortran code with Python

Scientific Computing

Article from ADMIN 54/2019
Fortran functions called from Python bring complex computations to a scriptable language.

Soon after C became the first language to be callable from Python, people wanted the same for the millions of lines of proven Fortran code in scientific applications. In the past, combining C and Fortran was dependent on the compiler. The advent of Fortran 2003 [1] brought a standard, compiler-independent C/Fortran interface.

The approach for combining C and Fortran for Python is to write a C wrapper for the Fortran functions and subroutines that you want to use in Python. Then, you build the Python function around the C wrapper and use it as a Python module. Calling the C function calls the Fortran routine. Although a little indirect, the concept is straightforward.

In the first example, I integrate Cython and Fortran.

Fortran/C and Cython

The Fortran 90 [2] website, which lists best practices, discusses how elements of the Fortran 2003 standard [3] can integrate C and Fortran. The iso_c_binding module of Fortran 2003-compliant compilers matches Fortran and C types with named constants used as KIND-type parameters in Fortran.

Without writing any C code, Cython can then be used to interface with the Fortran code. The Cython code is written in Fortran with the use of C calling conventions. The Fortran code interface with C uses the iso_c_binding module to link Cython directly against the Fortran library. Granted, this method doesn't really combine C and Fortran; rather, it uses the standardized Fortran/C interface. However, it really is integrating Fortran and C with Python.

If you are interested, the Fortran 90 website has an example of interfacing Fortran with Python via Cython that is as simple as creating a C interface in Fortran. Another good example can be found on

Use Express-Checkout link below to read the full article (PDF).

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy ADMIN Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

comments powered by Disqus