Variable reference from PyROOT


Please read tips for efficient and successful posting and posting code

ROOT Version: 6.18.04
_Platform: centos7
_Compiler: gcc9


Hello,

I’m trying to call a compiled c++ function in my python code. This cpp function expect a reference to a variable, which will be monitored in the function itself (e.g. when the variable is updated in the python code, I need that the c++ function is able to notice the updated value). Is that possible?

This function is like:

myfunc(const std::string& name, const double& var)

I tried to pass a ROOT object instantiated from the python code, but I’m not able to see any change.

Thank you all

I thing @etejedor can help you.

Hi,

In order to pass a double variable by reference in PyROOT, you need to use either ctypes.c_double or ROOT.Double . I would try first with ctypes.c_double because it is the one that we recommend in newer versions of ROOT, where ROOT.Double has been deprecated. But in 6.18 you should be able to use both. You would do something like this:

import ctypes
x = ctypes.c_double(1.)   # or ROOT.Double(1.)
myfunc(x)
print(x) # if myfunc modifies `x`, I can see the changes here

Hi @etejedor, thank you for the answer.

Unfortunately I just tried with ROOT.double(1.) and I’m not able to see changes, while with c_types I got an overloading run time error (none of the 9 overloaded methods succeeded, there are different methods for different types).

And is there a way to update values in the python code and see the changes in the c++ one (the c++ function is only used to “declare” values to this algorithm).

Thank you

Hi,

I just tried this example with 6.18, it should work for you too:

>>> import ROOT
>>> ROOT.gInterpreter.Declare("void foo(double& d) { d = 3; }")
True
>>> d = ROOT.Double(1)
>>> d
1.0
>>> ROOT.foo(d)
>>> d   # d was updated in C++
3.0

And here we create the value in Python and print it in C++:

>>> import ROOT
>>> ROOT.gInterpreter.Declare("void printme(double& d) { cout << d << endl; }")
True
>>> d = ROOT.Double(1)
>>> ROOT.printme(d)  # d was created in Python
1

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.