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?
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
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).
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