sharing variables in fortran
Greg Landrum
landrum at foreman.ac.rwth-aachen.de
Tue Apr 27 08:44:11 EDT 1999
Douglas du Boulay wrote:
>
> I am wondering if it is possible to coerce python to use
> memory addresses corresponding to a fortran common block (by way of a c
> extension)
> for storage of certain variables.
I can't speak to the python part of things, but there is a dirty
way to allow a C program to access fortran common blocks. I imagine
that this would allow you to solve your python problem fairly easily
by having your C wrapper muck around with the common blocks.
Before I tell you how to do it, I want to emphasize strongly that
this may not work with every compiler/OS combination. I figured
this out a while ago by playing around with the output of nm,
but I've never seen it written down anywhere. I've made this work
under AIX, Linux, HPUX, and IRIX, but that's no guarantee
that it'll go with everything.
Now that I have fired a healthy salvo of disclaimers, here's
the unpleasant method of solving the problem.
Here's a fragment of fortran code which uses a common block:
subroutine test_mod
real var1
integer var2
common /testblock/ var1,var2
print *, var1, var2
end
You can get at the contents of testblock by defining a global structure
in your C program which has exactly the same contents as testblock.
So, for example, this C program:
#include <stdio.h>
typedef struct {
float var1;
int var2;
} common1;
common1 testblock;
void main()
{
testblock.var1 = 1.034;
testblock.var2 = 2;
test_mod();
}
sets the members of the common block, then calls the fortran subroutine
which prints out its members.
Of course this repellant bit of magic doesn't work "as is" on every
system. Some f77 compilers like to stick one or more underscores after
subroutine and common block names. On those, you will have to change
the names of the common blocks in order to match. For example, g77
(at least my version) produces a .o file which has these symbols:
00000000 T test_mod__
00000008 C testblock_
(that's output from nm), so I have to change the call to test_mod
in the C part from test_mod() -> test_mod__().
Correspondingly, the name of testblock needs to be changed to
testblock_. It just can't be too easy.
Anyway, I hope that this type of trickery allows you to solve
your problems.
<hating-having-to-play-these-tricks>ly yours, [1]
-greg
[1] okay, okay, I haven't been following the group long enough
to have earned the right to do that, but I need to do *something*
to relieve the tension after thinking about these foul things
again.
---------------------
Dr. Greg Landrum (landrumSPAM at foreman.ac.rwth-aachen.de)
Institute of Inorganic Chemistry
Aachen University of Technology
Prof.-Pirlet-Str. 1, D-52074 Aachen, Germany
More information about the Python-list
mailing list