Python and Fortran code
Travis Oliphant
olipt at mayo.edu
Thu Jul 8 09:28:58 EDT 1999
> Hi!
> I have a quetion on using python to do some simple processing on
> some data I pre-process with some Fortran code. I wanted to be able to call
> this subroutine from within python, as it is already "tried and tested" and
> optimized. Basically, my subroutine looks like this:
>
> subroutine ex1(exdata)
> dimension exdata(256,200)
> print*,'Doing some processing in FORTRAN'
> C We said we were doing some processing, so we might as well do it :)
> C Processing of exdata
> return
> end
>
> This subroutine would need to get input from the user and would also
> need to print stuff out for the user to see several parameters as the
> software runs. I'd like to pass exdata as a Python object (NumPy array
> object), and then recover it with the results. I wonder if I could somehow
> do that compiling this subroutine as an object file and then calling it from
> python (not that i know how to do it, but with scilab, it works :D).
I don't know of any tool to call this routine "automatically" like in
scilab. Such a tool would be possible and wouldn't be difficult to get
"most of the way" but would be a bear to make work in all cases. Awhile
ago, I heard someone was working on something like that.
For now there are two options I know of.
(1) Mess around with dlmodule.c
which is "an experimental device to call arbitrary C functions in
arbitrary shared libraries." On linux with g77 your function would be
called ex1_ and you would pass it a Python string (which is a sequence of
bytes). I don't know much more about this option.
(2) Do what I did to construct multipack and other modules which link to
Fortran code: Write an extension module --- reference the documentation.
Briefly this involves writing two subroutines and compile them as a Python
module: The first is named initxxxxx and is what Python runs when
you say import xxxxx. The second is a function that takes two Python
objects. This is the function that will be run when you call the function
in Python. In here you get the NumPy array and pass a pointer to the
data of the array to ex1_ (remember the "_" on GNU/linux), then return.
If you need more help for option (2) just email. Option (1) I know less
about but would be interested to hear how that works.
Best,
Travis
More information about the Python-list
mailing list