Interfacing Fortran code from Python

@nedlrichards, welcome to the Forum! Yes, there several automatic wrapper generation tools, the most mature of which is f2py. See the links above.

Thanks to @hsnyder we now also have a prototype automatic wrapper in LFortran: src/lfortran/codegen/asr_to_py.cpp · 00c9351cad5f0606fb41cd6d8056e9dc4a52c9d5 · lfortran / lfortran · GitLab, currently it’s using iso_c_binding and Cython. If anyone is interested to contribute, definitely let us know. I am happy to get you up to speed.

Regarding allocatable arrays, you either have to allocate / deallocate from Fortran (just write some subroutines to do that and expose them to Python), or you have to allocate from Python or the Cython wrappers and only pass an already allocated array to Fortran. It’s much easier if you just use NumPy to allocate the arrays (numpy.empty()) and never store any pointers to it from Fortran, then there will be no memory leaks as NumPy will use Python’s GC to deallocate.

5 Likes