Hi,
I am trying to write a package that combines Python and Fortran. I'm currently struggling to figure out how to share a module variable. Specifically, I want to be able to modify the variable in the Python code and have the change reflected in Fortran and vice versa. The following are the contents of the source files:
m.f90
MODULE m
USE ISO_C_BINDING
integer(C_INT), bind(C, name="py_int") :: fort_int
END MODULE
f.f90 - simply sets variable to 99
subroutine f() bind(C, name="f")
use m, only : fort_int
use ISO_C_BINDING
fort_int = 99
END subroutine f
test.h
lib.pyx
def doit():
cdef extern from "test.h":
extern int py_int
void f()
py_int = 5
print "Before f(): ", py_int
f()
print "after f(): ", py_int
Compilation script:
cython lib.pyx
ifort -c m.f90 -fPIC
ifort -c f.f90 -fPIC
INCLUDES="-I/usr/include/python2.7"
LIBS="-lpthread -ldl -lutil -lm -lpython2.7"
eval icc -c lib.c -fPIC $INCLUDES $LIBS
eval icc -shared f.o m.o lib.o -o lib.so -fPIC $INCLUDES $LIBS
run.py - The program that runs it
from lib import doit
doit()
Output
Before f(): 5
after f(): 5 !! <- should be 99, since f() modifies the variable
My understanding is that by declaring "py_int" within a "cdef extern" block, Cython would make it an "extern int" that would ultimately point to the variable declared in m.f90. But apparently that is not happening.
Can someone point out the flaw in my understanding?
Thanks!