3

I have Fortran main code. I wish to call a python program from my main Fortran code and pass the array between these two codes.

I have seen several examples of F2py. It seems python codes serve as the main code. As I described before I want it the other way around.

Let us have a subroutine inside the main Fortran code as:

subroutine test(nx,ny,mask)
  integer, intent(in) :: nx, ny
  integer, dimension(nx,ny), intent(inout) :: mask
  
  call someOperation(nx, ny, mask)
end subroutine test

Now, someOperation is done in python and the multidimensional array with scalar values will be exchanged between Fortran and python.

How can it be done?

Ian Bush
  • 6,996
  • 1
  • 21
  • 27

1 Answers1

1

There are 2 large categories of ways:

  • mixed language programming (ie one single process)

    It is possible to embed a full Python interpretor in a compiled program (that is the way py2exe, pyinstaller or alii work), but it is a rather complex operation. Or you could write a Python extension able to call Fortran code for Python. It is simpler but still a good deal of work...

    Once it is done, you can "easily" call functions in one language from function in the other one. But parameter passing is not that easy even if swig can do a good job in that part.

    The last way in that category would be to use Cython. It is a Python interpretor that can natively call C functions: you will just have to interface C an Fortran, much easier.

  • 2 distinct processes (one for Fortran and one for Python)

    Here the main process will start the auxilliary one with the equivalent of popen or system and exchange serialized data over pipes, sockets or files. Probably less efficient but much simpler.

TL/DR: calling Python for a compiled program is neither a common operation nor a simple one: make sure you have no other ways to solve your problem. It you can, try to separate processing from the beginning between what has to be done in Python and what has to be done in Fortran and write distinct programs that you will just have to call one after the other. It would save you headaches and nightmares...

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252