Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
TPyClassGenerator.cxx
Go to the documentation of this file.
1// Author: Enric Tejedor CERN 08/2019
2// Original PyROOT code by Wim Lavrijsen, LBL
3//
4// /*************************************************************************
5// * Copyright (C) 1995-2019, Rene Brun and Fons Rademakers. *
6// * All rights reserved. *
7// * *
8// * For the licensing terms see $ROOTSYS/LICENSE. *
9// * For the list of contributors see $ROOTSYS/README/CREDITS. *
10// *************************************************************************/
11
12#include "Python.h"
13
14#include "TPyClassGenerator.h"
15#include "TPyReturn.h"
16
17// ROOT
18#include "TClass.h"
19#include "TInterpreter.h"
20#include "TROOT.h"
21#include "TList.h"
22
23// Standard
24#include <sstream>
25#include <string>
26#include <typeinfo>
27
28namespace {
29 class PyGILRAII {
30 PyGILState_STATE m_GILState;
31 public:
32 PyGILRAII() : m_GILState(PyGILState_Ensure()) { }
33 ~PyGILRAII() { PyGILState_Release(m_GILState); }
34 };
35}
36
37//- public members -----------------------------------------------------------
39{
40 // Just forward.
41 return GetClass(name, load, kFALSE);
42}
43
44//- public members -----------------------------------------------------------
46{
47 // Class generator to make python classes available to Cling
48
49 if (!load || !name)
50 return 0;
51
52 PyGILRAII thePyGILRAII;
53
54 // first, check whether the name is of a module
55 PyObject *modules = PySys_GetObject(const_cast<char *>("modules"));
59 Py_DecRef(keys);
61
62 if (isModule) {
63 // the normal TClass::GetClass mechanism doesn't allow direct returns, so
64 // do our own check
65 TClass *cl = (TClass *)gROOT->GetListOfClasses()->FindObject(name);
66 if (cl)
67 return cl;
68
69 std::ostringstream nsCode;
70 nsCode << "namespace " << name << " {\n";
71
72 // add all free functions
73 PyObject *bases = PyUnicode_FromString("__bases__");
74 PyObject *mod = PyDict_GetItemString(modules, const_cast<char *>(name));
76 keys = PyDict_Keys(dct);
77
78 for (int i = 0; i < PyList_GET_SIZE(keys); ++i) {
79 PyObject *key = PyList_GET_ITEM(keys, i);
80 Py_IncRef(key);
81
84
85 // TODO: refactor the code below with the class method code
87 std::string func_name = PyUnicode_AsUTF8(key);
88
89 // figure out number of variables required
90#if PY_VERSION_HEX < 0x30d00f0
91 PyObject *func_code = PyObject_GetAttrString(attr, (char *)"func_code");
92#else
93 PyObject *func_code = nullptr;
94 PyObject_GetOptionalAttrString(attr, (char *)"func_code", &func_code);
95#endif
96 PyObject *var_names = func_code ? PyObject_GetAttrString(func_code, (char *)"co_varnames") : NULL;
97 int nVars = var_names ? PyTuple_GET_SIZE(var_names) : 0 /* TODO: probably large number, all default? */;
98 if (nVars < 0)
99 nVars = 0;
102
103 nsCode << " TPyReturn " << func_name << "(";
104 for (int ivar = 0; ivar < nVars; ++ivar) {
105 nsCode << "const TPyArg& a" << ivar;
106 if (ivar != nVars - 1)
107 nsCode << ", ";
108 }
109 nsCode << ") {\n";
110 nsCode << " std::vector<TPyArg> v; v.reserve(" << nVars << ");\n";
111
112 // add the variables
113 for (int ivar = 0; ivar < nVars; ++ivar)
114 nsCode << " v.push_back(a" << ivar << ");\n";
115
116 // call dispatch (method or class pointer hard-wired)
117 nsCode << " return TPyReturn(TPyArg::CallMethod((PyObject*)" << std::showbase << (uintptr_t)attr << ", v)); }\n";
118 }
119
121 Py_DecRef(key);
122 }
123
124 Py_DecRef(keys);
126
127 nsCode << " }";
128
129 if (gInterpreter->LoadText(nsCode.str().c_str())) {
130 TClass *klass = new TClass(name, silent);
132 return klass;
133 }
134
135 return nullptr;
136 }
137
138 // determine module and class name part
139 std::string clName = name;
140 std::string::size_type pos = clName.rfind('.');
141
142 if (pos == std::string::npos)
143 return 0; // this isn't a python style class
144
145 std::string mdName = clName.substr(0, pos);
146 clName = clName.substr(pos + 1, std::string::npos);
147
148 // create class in namespace, if it exists (no load, silent)
149 Bool_t useNS = gROOT->GetListOfClasses()->FindObject(mdName.c_str()) != 0;
150 if (!useNS) {
151 // the class itself may exist if we're using the global scope
152 TClass *cl = (TClass *)gROOT->GetListOfClasses()->FindObject(clName.c_str());
153 if (cl)
154 return cl;
155 }
156
157 // locate and get class
158 PyObject *mod = PyImport_AddModule(const_cast<char *>(mdName.c_str()));
159 if (!mod) {
160 PyErr_Clear();
161 return 0; // module apparently disappeared
162 }
163
164 Py_IncRef(mod);
165 PyObject *pyclass = PyDict_GetItemString(PyModule_GetDict(mod), const_cast<char *>(clName.c_str()));
167 Py_DecRef(mod);
168
169 if (!pyclass) {
170 PyErr_Clear(); // the class is no longer available?!
171 return 0;
172 }
173
174 // get a listing of all python-side members
176 if (!attrs) {
177 PyErr_Clear();
179 return 0;
180 }
181
182 // pre-amble Cling proxy class
183 std::ostringstream proxyCode;
184 if (useNS)
185 proxyCode << "namespace " << mdName << " { ";
186 proxyCode << "class " << clName << " {\nprivate:\n PyObject* fPyObject;\npublic:\n";
187
188 // loop over and add member functions
190 for (int i = 0; i < PyList_GET_SIZE(attrs); ++i) {
191 PyObject *label = PyList_GET_ITEM(attrs, i);
192 Py_IncRef(label);
194
195 // collect only member functions (i.e. callable elements in __dict__)
196 if (PyCallable_Check(attr)) {
197 std::string mtName = PyUnicode_AsUTF8(label);
198
199 if (mtName == "__del__") {
201 proxyCode << " ~" << clName << "() { TPyArg::CallDestructor(fPyObject); }\n";
202 continue;
203 }
204
205 Bool_t isConstructor = mtName == "__init__";
206 if (!isConstructor && mtName.find("__", 0, 2) == 0)
207 continue; // skip all other python special funcs
208
209// figure out number of variables required
211 PyObject *var_names = func_code ? PyObject_GetAttrString(func_code, (char *)"co_varnames") : NULL;
212 if (PyErr_Occurred())
213 PyErr_Clear(); // happens for slots; default to 0 arguments
214
215 int nVars =
216 var_names ? PyTuple_GET_SIZE(var_names) - 1 /* self */ : 0 /* TODO: probably large number, all default? */;
217 if (nVars < 0)
218 nVars = 0;
221
222 // method declaration as appropriate
223 if (isConstructor) {
225 proxyCode << " " << clName << "(";
226 } else // normal method
227 proxyCode << " TPyReturn " << mtName << "(";
228 for (int ivar = 0; ivar < nVars; ++ivar) {
229 proxyCode << "const TPyArg& a" << ivar;
230 if (ivar != nVars - 1)
231 proxyCode << ", ";
232 }
233 proxyCode << ") {\n";
234 proxyCode << " std::vector<TPyArg> v; v.reserve(" << nVars + (isConstructor ? 0 : 1) << ");\n";
235
236 // add the 'self' argument as appropriate
237 if (!isConstructor)
238 proxyCode << " v.push_back(fPyObject);\n";
239
240 // then add the remaining variables
241 for (int ivar = 0; ivar < nVars; ++ivar)
242 proxyCode << " v.push_back(a" << ivar << ");\n";
243
244 // call dispatch (method or class pointer hard-wired)
245 if (!isConstructor)
246 proxyCode << " return TPyReturn(TPyArg::CallMethod((PyObject*)" << std::showbase << (uintptr_t)attr << ", v))";
247 else
248 proxyCode << " TPyArg::CallConstructor(fPyObject, (PyObject*)" << std::showbase << (uintptr_t)pyclass << ", v)";
249 proxyCode << ";\n }\n";
250 }
251
252 // no decref of attr for now (b/c of hard-wired ptr); need cleanup somehow
253 Py_DecRef(label);
254 }
255
256 // special case if no constructor or destructor
257 if (!hasConstructor)
258 proxyCode << " " << clName << "() {\n TPyArg::CallConstructor(fPyObject, (PyObject*)" << std::showbase << (uintptr_t)pyclass
259 << "); }\n";
260
261 if (!hasDestructor)
262 proxyCode << " ~" << clName << "() { TPyArg::CallDestructor(fPyObject); }\n";
263
264 // for now, don't allow copying (ref-counting wouldn't work as expected anyway)
265 proxyCode << " " << clName << "(const " << clName << "&) = delete;\n";
266 proxyCode << " " << clName << "& operator=(const " << clName << "&) = delete;\n";
267
268 // closing and building of Cling proxy class
269 proxyCode << "};";
270 if (useNS)
271 proxyCode << " }";
272
274 // done with pyclass, decref here, assuming module is kept
276
277 // body compilation
278 if (!gInterpreter->LoadText(proxyCode.str().c_str()))
279 return nullptr;
280
281 // done, let ROOT manage the new class
282 TClass *klass = new TClass(useNS ? (mdName + "::" + clName).c_str() : clName.c_str(), silent);
284
285 return klass;
286}
287
288////////////////////////////////////////////////////////////////////////////////
289/// Just forward; based on type name only.
290
292{
293 return GetClass(typeinfo.name(), load, silent);
294}
295
296////////////////////////////////////////////////////////////////////////////////
297/// Just forward; based on type name only
298
300{
301 return GetClass(typeinfo.name(), load);
302}
_object PyObject
constexpr Bool_t kFALSE
Definition RtypesCore.h:108
constexpr Bool_t kTRUE
Definition RtypesCore.h:107
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t attr
char name[80]
Definition TGX11.cxx:110
#define gInterpreter
#define gROOT
Definition TROOT.h:411
TClass instances represent classes, structs and namespaces in the ROOT type system.
Definition TClass.h:84
static void AddClass(TClass *cl)
static: Add a class to the list and map of classes.
Definition TClass.cxx:555
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:422
TClass * GetClass(const char *name, Bool_t load) override