Re: [f2py] Sharing data between fortran modules
Pearu Peterson <[email protected]> Wed, 10 Nov 2010 16:29:37 +0200
| Newsgroups | gmane.comp.python.f2py.user |
|---|---|
| Message-ID | <[email protected]> |
Hi, On 11/10/2010 03:49 PM, Eddy Thiriot wrote: > Hello everyone, > > I currently develop a program in Python that implements routines written > in FORTRAN for heavy numerical computations. For this propose, I use > f2py to wrap FORTRAN functions and global data contained in a single > module. Everything is ok but I deal with a behavior I don't really > understand. > > In order to make modular the program, I'd like to split the single > FORTRAN module into several parts, each one being compiled apart. Some > of the data are common to two or more parts. Below is a scheme of what I > tried to do. > > > FORTRAN modules: > > module mod1 > > integer,dimension(3) :: x > (other global data) > > contains > > (subroutines and functions) > > end module mod1 > > => compiled with : f2py -c -m mod1 mod1.F90 > > module mod2 > > integer,dimension(3) :: x > (other global data) > > contains > > (subroutines and functions) > > end module mod2 > > => compiled with : f2py -c -m mod2 mod2.F90 > > > Python script: > > import mod1, mod2 > > mod1.mod1.x = [1,1,1] > mod2.mod2.x = [2,2,2] > mod2.mod2.x = mod1.mod1.x > > > When I launch the Python script, mod1.x and mod2.x have the same value > (no problem !), but there is still the two objects mod1.x and mod2.x of > type<numpy.ndarray>. Indeed, the last statement make the setting of the > value(s) contained in array mod2.x from these in array mod1.x. I don't > understood why this statement doesn't set mod1.x and mod2.x with the > same reference (what I expected to obtain !). > This behavior is in opposite with a pure numpy Python script such as : > > import numpy > > a = numpy.asarray([1,1,1]) > b = numpy.asarray([2,2,2]) > b = a > > In this example, arrays a and b are the same instance of type > <numpy.ndarray> at the end. > > Please, could someone explain me the matter ? > Is it possible to make a sharing of data between several FORTRAN modules > (in the manner I want to do it) ? and, if possible, what is the "recipe" ? Short answer: no. Note that mod1.x is actually a view of the fortran data x from module mod1 and mod2.x is a view of x from module mod2. So there are two different memory chunks of data. Executing mod2.mod2.x = mod1.mod1.x *copies* data from one data chunk to another. The python statement b = a *re-references* b to point to data that is referenced by a. Note that data referenced originally by b is then discarded. It is not possible to share fortran data between different extension modules. This is related to the way how Python imports shared libraries. The only way to share Fortran data is to build wrappers to Fortran data to the same extension module. Fortran code can still be modular. So, do f2py -c -m mod mod1.F90 mod2.F90 (of course Fortran data x must be the same for both Fortran modules) Pearu