Fortran OOP from Python

Hello everybody! I know how to use Fortran in Python with CFFI Python library and iso_c_binding fortran module. But now I think I want to use fortran OOP possibilities in Python. Is there any tools or I need to use some low-level wrapper in my fortran code like c language style?

1 Like

There is f90wrap, discussed in a paper f90wrap: an automated tool for constructing deep Python interfaces to modern Fortran codes, by James Kermode, and @rgoswami has blogged about Simple Fortran Derived Types and Python.

It depends on detailed the Python side needs insight into the Fortran library. The easy case is when you only want to use your Fortran objects in Python, as you only have to export all hooks via bind(c). This step I’m at the moment doing mostly manually, because while well-defined, many objects have slightly different demands on the wrapper.

If you have a well-defined abstract base class you can implement this via a callback on the Fortran side, which takes C function and data pointer as implementation. I use this technique to implement logging for example. Viewing into Fortran data, dispatching an object based on its class or using memory allocators provided by a foreign runtime is more difficult. The former two are possible to implement, but can become a bit tedious, the latter I think is quite challenging with the current CFI features.

I gave a presentation on this topic a while ago, see

3 Likes