Global variable in dynamic loaded lib

Hi all ,

First of all thanks a lot for PyROOT : this is great work !

I’m having the following problem :
I have a piece of code that I compile with aclic and that I load into PyROOT with :
gSystem.Load(“myLib_cpp.so”)

In this lib I have :

int g_fitn;
void setfitN(int n){g_fitn=n;}
void printN(){ std::cout<< g_fitn<< std::endl;}

the variable is seen from python, but it does not correspond to the one of the lib :

[quote]

gSystem.Load(“myLib_cpp.so”)
g_fitn
0
g_fitn = 5
printN()
0
setfitN(3)
printN()
3[/quote]
Is there a way to have these variable known to python ? It would avoid the need of set/get method for global variables…

Thanks !

ps: using ROOT 5.13/02
pps: sorry, needed to edit the post

Hi,

the issue that you encounter is that the assignment to g_fitn is creating a new reference that scopes out the one in your library. Compare ordinary python:[code] >>> class A:
… fitn = 0

b = A.fitn
print b
0
b = 5
print A.fitn
0
[/code]

Likewise, you’ll need to scope your g_fitn, by accessing it where it’s coming from: the global ROOT namespace. That is, with your snippet of code in myLib.cpp, do the following:[code] >>> import ROOT

ROOT.gROOT.LoadMacro( ‘myLib.cpp+’ )
ROOT.g_fitn
0
ROOT.g_fitn = 5
ROOT.printN()
5
ROOT.setfitN(3)
ROOT.g_fitn
3
[/code]

Note that you can mix “from ROOT import *” and “import ROOT”. For example, to access the function directly (w/o ROOT.), and to scope global variables properly, as they would otherwise be masked like any other python reference.

HTH,
Wim

Very clear ! thanks a lot.
I have another question but I’ll open a new topic !