Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
ProxyWrappers.cxx
Go to the documentation of this file.
1// Bindings
2#include "CPyCppyy.h"
3#include "ProxyWrappers.h"
4#include "CPPClassMethod.h"
5#include "CPPConstructor.h"
6#include "CPPDataMember.h"
7#include "CPPExcInstance.h"
8#include "CPPFunction.h"
9#include "CPPGetSetItem.h"
10#include "CPPInstance.h"
11#include "CPPMethod.h"
12#include "CPPOverload.h"
13#include "CPPScope.h"
14#include "MemoryRegulator.h"
15#include "PyStrings.h"
16#include "Pythonize.h"
17#include "TemplateProxy.h"
18#include "TupleOfInstances.h"
19#include "TypeManip.h"
20#include "Utility.h"
21
22// Standard
23#include <algorithm>
24#include <deque>
25#include <map>
26#include <set>
27#include <string>
28#include <vector>
29
30
31//- data _______________________________________________________________________
32namespace CPyCppyy {
33 extern PyObject* gThisModule;
34 extern PyObject* gPyTypeMap;
35 extern std::set<Cppyy::TCppType_t> gPinnedTypes;
36}
37
38// to prevent having to walk scopes, track python classes by C++ class
39typedef std::map<Cppyy::TCppScope_t, PyObject*> PyClassMap_t;
41
42
43//- helpers --------------------------------------------------------------------
44
45namespace CPyCppyy {
46
47typedef struct {
48 PyObject_HEAD
51
52// helper for creating new C++ proxy python types
54{
55// Create a new python shadow class with the required hierarchy and meta-classes.
56 PyObject* pymetabases = PyTuple_New(PyTuple_GET_SIZE(pybases));
57 for (int i = 0; i < PyTuple_GET_SIZE(pybases); ++i) {
58 PyObject* btype = (PyObject*)Py_TYPE(PyTuple_GetItem(pybases, i));
59 Py_INCREF(btype);
60 PyTuple_SET_ITEM(pymetabases, i, btype);
61 }
62
63 std::string name = Cppyy::GetFinalName(klass);
64
65// create meta-class, add a dummy __module__ to pre-empt the default setting
66 PyObject* args = Py_BuildValue((char*)"sO{}", (name+"_meta").c_str(), pymetabases);
67 PyDict_SetItem(PyTuple_GET_ITEM(args, 2), PyStrings::gModule, Py_True);
68 Py_DECREF(pymetabases);
69
70 PyObject* pymeta = (PyObject*)CPPScopeMeta_New(klass, args);
71 Py_DECREF(args);
72 if (!pymeta) {
73 PyErr_Print();
74 return nullptr;
75 }
76
77// alright, and now we really badly want to get rid of the dummy ...
78 PyObject* dictproxy = PyObject_GetAttr(pymeta, PyStrings::gDict);
79 PyDict_DelItem(((proxyobject*)dictproxy)->dict, PyStrings::gModule);
80
81// create actual class
82 args = Py_BuildValue((char*)"sO{}", name.c_str(), pybases);
83 PyObject* pyclass =
84 ((PyTypeObject*)pymeta)->tp_new((PyTypeObject*)pymeta, args, nullptr);
85
86 Py_DECREF(args);
87 Py_DECREF(pymeta);
88
89 return pyclass;
90}
91
92static inline
95{
97 PyObject* pname = CPyCppyy_PyText_InternFromString(const_cast<char*>(property->GetName().c_str()));
98
99// allow access at the instance level
100 PyType_Type.tp_setattro(pyclass, pname, (PyObject*)property);
101
102// allow access at the class level (always add after setting instance level)
103 if (Cppyy::IsStaticData(scope, idata))
104 PyType_Type.tp_setattro((PyObject*)Py_TYPE(pyclass), pname, (PyObject*)property);
105
106// cleanup
107 Py_DECREF(pname);
108 Py_DECREF(property);
109}
110
111static inline
112void AddScopeToParent(PyObject* parent, const std::string& name, PyObject* newscope)
113{
115 if (CPPScope_Check(parent)) PyType_Type.tp_setattro(parent, pyname, newscope);
116 else PyObject_SetAttr(parent, pyname, newscope);
117 Py_DECREF(pyname);
118}
119
120static inline
122// get an attribute without causing getattr lookups
123 PyObject* dct = PyObject_GetAttr(pyclass, PyStrings::gDict);
124 if (dct) {
125 PyObject* attr = PyObject_GetItem(dct, pyname);
126 Py_DECREF(dct);
127 return attr;
128 }
129 return nullptr;
130}
131
132} // namespace CPyCppyy
133
134
135//- public functions ---------------------------------------------------------
136namespace CPyCppyy {
137
138static inline void sync_templates(
139 PyObject* pyclass, const std::string& mtCppName, const std::string& mtName)
140{
141 PyObject* dct = PyObject_GetAttr(pyclass, PyStrings::gDict);
142 PyObject* pyname = CPyCppyy_PyText_InternFromString(const_cast<char*>(mtName.c_str()));
143 PyObject* attr = PyObject_GetItem(dct, pyname);
144 if (!attr) PyErr_Clear();
145 Py_DECREF(dct);
147 TemplateProxy* pytmpl = TemplateProxy_New(mtCppName, mtName, pyclass);
149 PyType_Type.tp_setattro(pyclass, pyname, (PyObject*)pytmpl);
150 Py_DECREF(pytmpl);
151 }
152 Py_XDECREF(attr);
153 Py_DECREF(pyname);
154}
155
157{
158// Collect methods and data for the given scope, and add them to the given python
159// proxy object.
160
161// some properties that'll affect building the dictionary
162 bool isNamespace = Cppyy::IsNamespace(scope);
163 bool isAbstract = Cppyy::IsAbstract(scope);
164 bool hasConstructor = false;
166
167// load all public methods and data members
168 typedef std::vector<PyCallable*> Callables_t;
169 typedef std::map<std::string, Callables_t> CallableCache_t;
170 CallableCache_t cache;
171
172// bypass custom __getattr__ for efficiency
173 getattrofunc oldgetattro = Py_TYPE(pyclass)->tp_getattro;
174 Py_TYPE(pyclass)->tp_getattro = PyType_Type.tp_getattro;
175
176// functions in namespaces are properly found through lazy lookup, so do not
177// create them until needed (the same is not true for data members)
178 const Cppyy::TCppIndex_t nMethods = isNamespace ? 0 : Cppyy::GetNumMethods(scope);
179 for (Cppyy::TCppIndex_t imeth = 0; imeth < nMethods; ++imeth) {
180 Cppyy::TCppMethod_t method = Cppyy::GetMethod(scope, imeth);
181
182 // process the method based on its name
183 std::string mtCppName = Cppyy::GetMethodName(method);
184
185 // special case trackers
186 bool setupSetItem = false;
187 bool isConstructor = Cppyy::IsConstructor(method);
188 bool isTemplate = isConstructor ? false : Cppyy::IsMethodTemplate(scope, imeth);
189
190 // filter empty names (happens for namespaces, is bug?)
191 if (mtCppName == "")
192 continue;
193
194 // filter C++ destructors
195 if (mtCppName[0] == '~')
196 continue;
197
198 // translate operators
199 std::string mtName = Utility::MapOperatorName(mtCppName, Cppyy::GetMethodNumArgs(method));
200 if (mtName.empty())
201 continue;
202
203 // operator[]/() returning a reference type will be used for __setitem__
204 bool isCall = mtName == "__call__";
205 if (isCall || mtName == "__getitem__") {
206 const std::string& qual_return = Cppyy::ResolveName(Cppyy::GetMethodResultType(method));
207 const std::string& cpd = Utility::Compound(qual_return);
208 if (!cpd.empty() && cpd[cpd.size()- 1] == '&' && \
209 qual_return.find("const", 0, 5) == std::string::npos) {
210 if (isCall && !potGetItem) potGetItem = method;
211 setupSetItem = true; // will add methods as overloads
212 } else if (isCall && 1 < Cppyy::GetMethodNumArgs(method)) {
213 // not a non-const by-ref return, thus better __getitem__ candidate; the
214 // requirement for multiple arguments is that there is otherwise no benefit
215 // over the use of normal __getitem__ (this allows multi-indexing argumenst,
216 // which is clean in Python, but not allowed in C++)
217 potGetItem = method;
218 }
219 }
220
221 // do not expose private methods as the Cling wrappers for them won't compile
222 if (!Cppyy::IsPublicMethod(method))
223 continue;
224
225 // template members; handled by adding a dispatcher to the class
226 bool storeOnTemplate =
227 isTemplate ? true : (!isConstructor && Cppyy::ExistsMethodTemplate(scope, mtCppName));
228 if (storeOnTemplate) {
229 sync_templates(pyclass, mtCppName, mtName);
230 // continue processing to actually add the method so that the proxy can find
231 // it on the class when called explicitly
232 }
233
234 // construct the holder
235 PyCallable* pycall = nullptr;
236 if (Cppyy::IsStaticMethod(method)) // class method
237 pycall = new CPPClassMethod(scope, method);
238 else if (isNamespace) // free function
239 pycall = new CPPFunction(scope, method);
240 else if (isConstructor) { // ctor
241 mtName = "__init__";
242 hasConstructor = true;
243 if (!isAbstract)
244 pycall = new CPPConstructor(scope, method);
245 else
246 pycall = new CPPAbstractClassConstructor(scope, method);
247 } else // member function
248 pycall = new CPPMethod(scope, method);
249
250 if (storeOnTemplate) {
251 // template proxy was already created in sync_templates call above, so
252 // add only here, not to the cache of collected methods
253 PyObject* attr = PyObject_GetAttrString(pyclass, const_cast<char*>(mtName.c_str()));
254 if (isTemplate) ((TemplateProxy*)attr)->AdoptTemplate(pycall);
255 else ((TemplateProxy*)attr)->AdoptMethod(pycall);
256 Py_DECREF(attr);
257
258 // for operator[]/() that returns by ref, also add __setitem__
259 if (setupSetItem) {
261 if (!TemplateProxy_Check(pysi)) {
262 CPPOverload* precursor = (CPPOverload_Check(pysi)) ? (CPPOverload*)pysi : nullptr;
263 if (pysi && !precursor) Py_DECREF(pysi); // something unknown, just drop it
264 pysi = TemplateProxy_New(mtCppName, "__setitem__", pyclass);
265 if (precursor) pysi->MergeOverload(precursor);
266 Py_XDECREF(precursor);
267 PyObject_SetAttrString(pyclass, const_cast<char*>("__setitem__"), (PyObject*)pysi);
268 }
269 if (isTemplate) pysi->AdoptTemplate(new CPPSetItem(scope, method));
270 else pysi->AdoptMethod(new CPPSetItem(scope, method));
271 Py_XDECREF(pysi);
272 }
273
274 } else {
275 // lookup method dispatcher and store method
276 Callables_t& md = (*(cache.insert(
277 std::make_pair(mtName, Callables_t())).first)).second;
278 md.push_back(pycall);
279
280 // special case for operator[]/() that returns by ref, use for getitem/call and setitem
281 if (setupSetItem) {
282 Callables_t& setitem = (*(cache.insert(
283 std::make_pair(std::string("__setitem__"), Callables_t())).first)).second;
284 setitem.push_back(new CPPSetItem(scope, method));
285 }
286 }
287 }
288
289// add proxies for un-instantiated/non-overloaded templated methods
290 const Cppyy::TCppIndex_t nTemplMethods = isNamespace ? 0 : Cppyy::GetNumTemplatedMethods(scope);
291 for (Cppyy::TCppIndex_t imeth = 0; imeth < nTemplMethods; ++imeth) {
292 const std::string mtCppName = Cppyy::GetTemplatedMethodName(scope, imeth);
293 // the number of arguments isn't known until instantiation and as far as C++ is concerned, all
294 // same-named operators are simply overloads; so will pre-emptively add both names if with and
295 // without arguments differ, letting the normal overload mechanism resolve on call
296 bool isConstructor = Cppyy::IsTemplatedConstructor(scope, imeth);
297
298 // first add with no arguments
299 std::string mtName0 = isConstructor ? "__init__" : Utility::MapOperatorName(mtCppName, false);
300 sync_templates(pyclass, mtCppName, mtName0);
301
302 // then add when taking arguments, if this method is different
303 if (!isConstructor) {
304 std::string mtName1 = Utility::MapOperatorName(mtCppName, true);
305 if (mtName0 != mtName1)
306 sync_templates(pyclass, mtCppName, mtName1);
307 }
308 }
309
310// add a pseudo-default ctor, if none defined
311 if (!hasConstructor) {
312 PyCallable* defctor = nullptr;
313 if (isAbstract)
314 defctor = new CPPAbstractClassConstructor(scope, (Cppyy::TCppMethod_t)0);
315 else if (isNamespace)
316 defctor = new CPPNamespaceConstructor(scope, (Cppyy::TCppMethod_t)0);
318 ((CPPScope*)pyclass)->fFlags |= CPPScope::kIsInComplete;
319 defctor = new CPPIncompleteClassConstructor(scope, (Cppyy::TCppMethod_t)0);
320 } else
321 defctor = new CPPConstructor(scope, (Cppyy::TCppMethod_t)0);
322 cache["__init__"].push_back(defctor);
323 }
324
325// map __call__ to __getitem__ if also mapped to __setitem__
326 if (potGetItem) {
327 Callables_t& getitem = (*(cache.insert(
328 std::make_pair(std::string("__getitem__"), Callables_t())).first)).second;
329 getitem.push_back(new CPPGetItem(scope, potGetItem));
330 }
331
332// add the methods to the class dictionary
333 PyObject* dct = PyObject_GetAttr(pyclass, PyStrings::gDict);
334 for (CallableCache_t::iterator imd = cache.begin(); imd != cache.end(); ++imd) {
335 // in order to prevent removing templated editions of this method (which were set earlier,
336 // above, as a different proxy object), we'll check and add this method flagged as a generic
337 // one (to be picked up by the templated one as appropriate) if a template exists
338 PyObject* pyname = CPyCppyy_PyText_FromString(const_cast<char*>(imd->first.c_str()));
339 PyObject* attr = PyObject_GetItem(dct, pyname);
340 Py_DECREF(pyname);
342 // template exists, supply it with the non-templated method overloads
343 for (auto cit : imd->second)
344 ((TemplateProxy*)attr)->AdoptMethod(cit);
345 } else {
346 if (!attr) PyErr_Clear();
347 // normal case, add a new method
348 CPPOverload* method = CPPOverload_New(imd->first, imd->second);
349 PyObject* pymname = CPyCppyy_PyText_InternFromString(const_cast<char*>(method->GetName().c_str()));
350 PyType_Type.tp_setattro(pyclass, pymname, (PyObject*)method);
351 Py_DECREF(pymname);
352 Py_DECREF(method);
353 }
354
355 Py_XDECREF(attr); // could have been found in base class or non-existent
356 }
357 Py_DECREF(dct);
358
359 // collect data members (including enums)
360 const Cppyy::TCppIndex_t nDataMembers = Cppyy::GetNumDatamembers(scope);
361 for (Cppyy::TCppIndex_t idata = 0; idata < nDataMembers; ++idata) {
362 // allow only public members
363 if (!Cppyy::IsPublicData(scope, idata))
364 continue;
365
366 // enum datamembers (this in conjunction with previously collected enums above)
367 if (Cppyy::IsEnumData(scope, idata) && Cppyy::IsStaticData(scope, idata)) {
368 // some implementation-specific data members have no address: ignore them
369 if (!Cppyy::GetDatamemberOffset(scope, idata))
370 continue;
371
372 // two options: this is a static variable, or it is the enum value, the latter
373 // already exists, so check for it and move on if set
374 PyObject* eset = PyObject_GetAttrString(pyclass,
375 const_cast<char*>(Cppyy::GetDatamemberName(scope, idata).c_str()));
376 if (eset) {
377 Py_DECREF(eset);
378 continue;
379 }
380
381 PyErr_Clear();
382
383 // it could still be that this is an unnamed enum, which is not in the list
384 // provided by the class
385 if (strstr(Cppyy::GetDatamemberType(scope, idata).c_str(), "(unnamed)") != 0) {
386 AddPropertyToClass(pyclass, scope, idata);
387 continue;
388 }
389 }
390
391 // properties (aka public (static) data members)
392 AddPropertyToClass(pyclass, scope, idata);
393 }
394
395// restore custom __getattr__
396 Py_TYPE(pyclass)->tp_getattro = oldgetattro;
397
398// all ok, done
399 return 0;
400}
401
402//----------------------------------------------------------------------------
403static void CollectUniqueBases(Cppyy::TCppType_t klass, std::deque<std::string>& uqb)
404{
405// collect bases in acceptable mro order, while removing duplicates (this may
406// break the overload resolution in esoteric cases, but otherwise the class can
407// not be used at all, as CPython will refuse the mro).
408 size_t nbases = Cppyy::GetNumBases(klass);
409
410 std::deque<Cppyy::TCppType_t> bids;
411 for (size_t ibase = 0; ibase < nbases; ++ibase) {
412 const std::string& name = Cppyy::GetBaseName(klass, ibase);
413 int decision = 2;
415 if (!tp) continue; // means this base with not be available Python-side
416 for (size_t ibase2 = 0; ibase2 < uqb.size(); ++ibase2) {
417 if (uqb[ibase2] == name) { // not unique ... skip
418 decision = 0;
419 break;
420 }
421
422 if (Cppyy::IsSubtype(tp, bids[ibase2])) {
423 // mro requirement: sub-type has to follow base
424 decision = 1;
425 break;
426 }
427 }
428
429 if (decision == 1) {
430 uqb.push_front(name);
431 bids.push_front(tp);
432 } else if (decision == 2) {
433 uqb.push_back(name);
434 bids.push_back(tp);
435 }
436 // skipped if decision == 0 (not unique)
437 }
438}
439
441{
442// Build a tuple of python proxy classes of all the bases of the given 'klass'.
443 std::deque<std::string> uqb;
444 CollectUniqueBases(klass, uqb);
445
446// allocate a tuple for the base classes, special case for first base
447 size_t nbases = uqb.size();
448
449 PyObject* pybases = PyTuple_New(nbases ? nbases : 1);
450 if (!pybases)
451 return nullptr;
452
453// build all the bases
454 if (nbases == 0) {
455 Py_INCREF((PyObject*)(void*)&CPPInstance_Type);
456 PyTuple_SET_ITEM(pybases, 0, (PyObject*)(void*)&CPPInstance_Type);
457 } else {
458 for (std::deque<std::string>::size_type ibase = 0; ibase < nbases; ++ibase) {
459 PyObject* pyclass = CreateScopeProxy(uqb[ibase]);
460 if (!pyclass) {
461 Py_DECREF(pybases);
462 return nullptr;
463 }
464
465 PyTuple_SET_ITEM(pybases, ibase, pyclass);
466 }
467
468 // special case, if true python types enter the hierarchy, make sure that
469 // the first base seen is still the CPPInstance_Type
470 if (!PyObject_IsSubclass(PyTuple_GET_ITEM(pybases, 0), (PyObject*)&CPPInstance_Type)) {
471 PyObject* newpybases = PyTuple_New(nbases+1);
472 Py_INCREF((PyObject*)(void*)&CPPInstance_Type);
473 PyTuple_SET_ITEM(newpybases, 0, (PyObject*)(void*)&CPPInstance_Type);
474 for (int ibase = 0; ibase < (int)nbases; ++ibase) {
475 PyObject* pyclass = PyTuple_GET_ITEM(pybases, ibase);
476 Py_INCREF(pyclass);
477 PyTuple_SET_ITEM(newpybases, ibase+1, pyclass);
478 }
479 Py_DECREF(pybases);
480 pybases = newpybases;
481 }
482 }
483
484 return pybases;
485}
486
487} // namespace CPyCppyy
488
489//----------------------------------------------------------------------------
491{
492// Retrieve scope proxy from the known ones.
493 PyClassMap_t::iterator pci = gPyClasses.find(scope);
494 if (pci != gPyClasses.end()) {
495 PyObject* pyclass = PyWeakref_GetObject(pci->second);
496 if (pyclass != Py_None) {
497 Py_INCREF(pyclass);
498 return pyclass;
499 }
500 }
501
502 return nullptr;
503}
504
505//----------------------------------------------------------------------------
507{
508// Convenience function with a lookup first through the known existing proxies.
509 PyObject* pyclass = GetScopeProxy(scope);
510 if (pyclass)
511 return pyclass;
512
514}
515
516//----------------------------------------------------------------------------
518{
519// Build a python shadow class for the named C++ class.
520 std::string cname = CPyCppyy_PyText_AsString(PyTuple_GetItem(args, 0));
521 if (PyErr_Occurred())
522 return nullptr;
523
524 return CreateScopeProxy(cname);
525}
526
527//----------------------------------------------------------------------------
529{
530// Build a python shadow class for the named C++ class or namespace.
531
532// determine complete scope name, if a python parent has been given
533 std::string scName = "";
534 if (parent) {
535 if (CPPScope_Check(parent))
536 scName = Cppyy::GetScopedFinalName(((CPPScope*)parent)->fCppType);
537 else {
538 PyObject* parname = PyObject_GetAttr(parent, PyStrings::gName);
539 if (!parname) {
540 PyErr_Format(PyExc_SystemError, "given scope has no name for %s", name.c_str());
541 return nullptr;
542 }
543
544 // should be a string
545 scName = CPyCppyy_PyText_AsString(parname);
546 Py_DECREF(parname);
547 if (PyErr_Occurred())
548 return nullptr;
549 }
550
551 // accept this parent scope and use it's name for prefixing
552 Py_INCREF(parent);
553 }
554
555// retrieve C++ class (this verifies name, and is therefore done first)
556 const std::string& lookup = scName.empty() ? name : (scName+"::"+name);
557 Cppyy::TCppScope_t klass = Cppyy::GetScope(lookup);
558
559 if (!(bool)klass && Cppyy::IsTemplate(lookup)) {
560 // a "naked" templated class is requested: return callable proxy for instantiations
561 PyObject* pytcl = PyObject_GetAttr(gThisModule, PyStrings::gTemplate);
562 PyObject* pytemplate = PyObject_CallFunction(
563 pytcl, const_cast<char*>("s"), const_cast<char*>(lookup.c_str()));
564 Py_DECREF(pytcl);
565
566 // cache the result
567 AddScopeToParent(parent ? parent : gThisModule, name, pytemplate);
568
569 // done, next step should be a call into this template
570 Py_XDECREF(parent);
571 return pytemplate;
572 }
573
574 if (!(bool)klass) {
575 // could be an enum, which are treated seperately in CPPScope (TODO: maybe they
576 // should be handled here instead anyway??)
577 if (Cppyy::IsEnum(lookup))
578 return nullptr;
579
580 // final possibility is a typedef of a builtin; these are mapped on the python side
581 std::string resolved = Cppyy::ResolveName(lookup);
582 if (gPyTypeMap) {
583 PyObject* tc = PyDict_GetItemString(gPyTypeMap, resolved.c_str()); // borrowed
584 if (tc && PyCallable_Check(tc)) {
585 PyObject* nt = PyObject_CallFunction(tc, (char*)"ss", name.c_str(), scName.c_str());
586 if (nt) {
587 if (parent) {
588 AddScopeToParent(parent, name, nt);
589 Py_DECREF(parent);
590 }
591 return nt;
592 }
593 PyErr_Clear();
594 }
595 }
596
597 // all options have been exhausted: it doesn't exist as such
598 PyErr_Format(PyExc_TypeError, "\'%s\' is not a known C++ class", lookup.c_str());
599 Py_XDECREF(parent);
600 return nullptr;
601 }
602
603// locate class by ID, if possible, to prevent parsing scopes/templates anew
604 PyObject* pyscope = GetScopeProxy(klass);
605 if (pyscope) {
606 if (parent) {
607 AddScopeToParent(parent, name, pyscope);
608 Py_DECREF(parent);
609 }
610 return pyscope;
611 }
612
613// now have a class ... get the actual, fully scoped class name, so that typedef'ed
614// classes are created in the right place
615 const std::string& actual = Cppyy::GetScopedFinalName(klass);
616 if (actual != lookup) {
617 pyscope = CreateScopeProxy(actual);
618 if (!pyscope) PyErr_Clear();
619 }
620
621// locate the parent, if necessary, for memoizing the class if not specified
622 std::string::size_type last = 0;
623 if (!parent) {
624 // TODO: move this to TypeManip, which already has something similar in
625 // the form of 'extract_namespace'
626 // need to deal with template parameters that can have scopes themselves
627 int tpl_open = 0;
628 for (std::string::size_type pos = 0; pos < name.size(); ++pos) {
629 std::string::value_type c = name[pos];
630
631 // count '<' and '>' to be able to skip template contents
632 if (c == '<')
633 ++tpl_open;
634 else if (c == '>')
635 --tpl_open;
636
637 // by only checking for "::" the last part (class name) is dropped
638 else if (tpl_open == 0 && \
639 c == ':' && pos+1 < name.size() && name[ pos+1 ] == ':') {
640 // found a new scope part
641 const std::string& part = name.substr(last, pos-last);
642
643 PyObject* next = PyObject_GetAttrString(
644 parent ? parent : gThisModule, const_cast<char*>(part.c_str()));
645
646 if (!next) { // lookup failed, try to create it
647 PyErr_Clear();
648 next = CreateScopeProxy(part, parent);
649 }
650 Py_XDECREF(parent);
651
652 if (!next) // create failed, give up
653 return nullptr;
654
655 // found scope part
656 parent = next;
657
658 // done with part (note that pos is moved one ahead here)
659 last = pos+2; ++pos;
660 }
661 }
662
663 if (!parent && name.size() > 0) {
664 // Didn't find any scope in the name, so must be global
666 }
667
668 if (parent && !CPPScope_Check(parent)) {
669 // Special case: parent found is not one of ours (it's e.g. a pure Python module), so
670 // continuing would fail badly. One final lookup, then out of here ...
671 std::string unscoped = name.substr(last, std::string::npos);
672 PyObject* ret = PyObject_GetAttrString(parent, unscoped.c_str());
673 Py_DECREF(parent);
674 return ret;
675 }
676 }
677
678// use the module as a fake scope if no outer scope found
679 if (!parent) {
680 Py_INCREF(gThisModule);
681 parent = gThisModule;
682 }
683
684// if the scope was earlier found as actual, then we're done already, otherwise
685// build a new scope proxy
686 if (!pyscope) {
687 // construct the base classes
688 PyObject* pybases = BuildCppClassBases(klass);
689 if (pybases != 0) {
690 // create a fresh Python class, given bases, name, and empty dictionary
691 pyscope = CreateNewCppProxyClass(klass, pybases);
692 Py_DECREF(pybases);
693 }
694
695 // fill the dictionary, if successful
696 if (pyscope) {
697 if (BuildScopeProxyDict(klass, pyscope)) {
698 // something failed in building the dictionary
699 Py_DECREF(pyscope);
700 pyscope = nullptr;
701 }
702 }
703
704 // store a ref from cppyy scope id to new python class
705 if (pyscope && !(((CPPScope*)pyscope)->fFlags & CPPScope::kIsInComplete)) {
706 gPyClasses[klass] = PyWeakref_NewRef(pyscope, nullptr);
707
708 if (!(((CPPScope*)pyscope)->fFlags & CPPScope::kIsNamespace)) {
709 // add python-style features to classes only
710 if (!Pythonize(pyscope, Cppyy::GetScopedFinalName(klass))) {
711 Py_DECREF(pyscope);
712 pyscope = nullptr;
713 }
714 } else {
715 // add to sys.modules to allow importing from this namespace
716 PyObject* pyfullname = PyObject_GetAttr(pyscope, PyStrings::gModule);
718 CPyCppyy_PyText_AppendAndDel(&pyfullname, PyObject_GetAttr(pyscope, PyStrings::gName));
719 PyObject* modules = PySys_GetObject(const_cast<char*>("modules"));
720 if (modules && PyDict_Check(modules))
721 PyDict_SetItem(modules, pyfullname, pyscope);
722 Py_DECREF(pyfullname);
723 }
724 }
725 }
726
727// store on parent if found/created and complete
728 if (pyscope && !(((CPPScope*)pyscope)->fFlags & CPPScope::kIsInComplete))
729 AddScopeToParent(parent, name, pyscope);
730 Py_DECREF(parent);
731
732// all done
733 return pyscope;
734}
735
736
737//----------------------------------------------------------------------------
739{
740// To allow use of C++ exceptions in lieue of Python exceptions, they need to
741// derive from BaseException, which can not mix with the normal CPPInstance and
742// use of the meta-class. Instead, encapsulate them in a forwarding class that
743// derives from Pythons Exception class
744
745// start with creation of CPPExcInstance type base classes
746 std::deque<std::string> uqb;
747 CollectUniqueBases(((CPPScope*)pyscope)->fCppType, uqb);
748 size_t nbases = uqb.size();
749
750// Support for multiple bases actually can not actually work as-is: the reason
751// for deriving from BaseException is to guarantee the layout needed for storing
752// traces. If some other base is std::exception (as e.g. boost::bad_any_cast) or
753// also derives from std::exception, then there are two trace locations. OTOH,
754// if the other class is a non-exception type, then the exception class does not
755// need to derive from it because it can never be caught as that type forwarding
756// to the proxy will work as expected, through, which is good enough).
757//
758// The code below restricts the hierarchy to a single base class, picking the
759// "best" by filtering std::exception and non-exception bases.
760
761 PyObject* pybases = PyTuple_New(1);
762 if (nbases == 0) {
763 Py_INCREF((PyObject*)(void*)&CPPExcInstance_Type);
764 PyTuple_SET_ITEM(pybases, 0, (PyObject*)(void*)&CPPExcInstance_Type);
765 } else {
766 PyObject* best_base = nullptr;
767
768 for (std::deque<std::string>::size_type ibase = 0; ibase < nbases; ++ibase) {
769 // retrieve bases through their enclosing scope to guarantee treatment as
770 // exception classes and proper caching
771 const std::string& finalname = Cppyy::GetScopedFinalName(Cppyy::GetScope(uqb[ibase]));
772 const std::string& parentname = TypeManip::extract_namespace(finalname);
773 PyObject* base_parent = CreateScopeProxy(parentname);
774 if (!base_parent) {
775 Py_DECREF(pybases);
776 return nullptr;
777 }
778
779 PyObject* excbase = PyObject_GetAttrString(base_parent,
780 parentname.empty() ? finalname.c_str() : finalname.substr(parentname.size()+2, std::string::npos).c_str());
781 Py_DECREF(base_parent);
782 if (!excbase) {
783 Py_DECREF(pybases);
784 return nullptr;
785 }
786
787 if (PyType_IsSubtype((PyTypeObject*)excbase, &CPPExcInstance_Type)) {
788 Py_XDECREF(best_base);
789 best_base = excbase;
790 if (finalname != "std::exception")
791 break;
792 } else {
793 // just skip: there will be at least one exception derived base class
794 Py_DECREF(excbase);
795 }
796 }
797
798 PyTuple_SET_ITEM(pybases, 0, best_base);
799 }
800
801 PyObject* args = Py_BuildValue((char*)"OO{}", pyname, pybases);
802
803// meta-class attributes (__cpp_name__, etc.) can not be resolved lazily so add
804// them directly instead in case they are needed
805 PyObject* dct = PyTuple_GET_ITEM(args, 2);
806 PyDict_SetItem(dct, PyStrings::gUnderlying, pyscope);
807 PyDict_SetItem(dct, PyStrings::gName, PyObject_GetAttr(pyscope, PyStrings::gName));
808 PyDict_SetItem(dct, PyStrings::gCppName, PyObject_GetAttr(pyscope, PyStrings::gCppName));
809 PyDict_SetItem(dct, PyStrings::gModule, PyObject_GetAttr(pyscope, PyStrings::gModule));
810
811// create the actual exception class
812 PyObject* exc_pyscope = PyType_Type.tp_new(&PyType_Type, args, nullptr);
813 Py_DECREF(args);
814 Py_DECREF(pybases);
815
816// cache the result for future lookups and return
817 PyType_Type.tp_setattro(parent, pyname, exc_pyscope);
818 return exc_pyscope;
819}
820
821
822//----------------------------------------------------------------------------
824 Cppyy::TCppType_t klass, const unsigned flags)
825{
826// only known or knowable objects will be bound (null object is ok)
827 if (!klass) {
828 PyErr_SetString(PyExc_TypeError, "attempt to bind C++ object w/o class");
829 return nullptr;
830 }
831
832// retrieve python class
833 PyObject* pyclass = CreateScopeProxy(klass);
834 if (!pyclass)
835 return nullptr; // error has been set in CreateScopeProxy
836
837 bool isRef = flags & CPPInstance::kIsReference;
838 bool isValue = flags & CPPInstance::kIsValue;
839
840// TODO: make sure that a consistent address is used (may have to be done in BindCppObject)
841 if (address && !isValue /* always fresh */ && !(flags & (CPPInstance::kNoWrapConv|CPPInstance::kNoMemReg))) {
842 PyObject* oldPyObject = MemoryRegulator::RetrievePyObject(
843 isRef ? *(void**)address : address, pyclass);
844
845 // ptr-ptr requires old object to be a reference to enable re-use
846 if (oldPyObject && (!(flags & CPPInstance::kIsPtrPtr) ||
847 ((CPPInstance*)oldPyObject)->fFlags & CPPInstance::kIsReference)) {
848 return oldPyObject;
849 }
850 }
851
852// if smart, instantiate a Python-side object of the underlying type, carrying the smartptr
853 PyObject* smart_type = (flags != CPPInstance::kNoWrapConv && (((CPPClass*)pyclass)->fFlags & CPPScope::kIsSmart)) ? pyclass : nullptr;
854 if (smart_type) {
855 pyclass = CreateScopeProxy(((CPPSmartClass*)smart_type)->fUnderlyingType);
856 if (!pyclass) {
857 // simply restore and expose as the actual smart pointer class
858 pyclass = smart_type;
859 smart_type = nullptr;
860 }
861 }
862
863// instantiate an object of this class
864 PyObject* args = PyTuple_New(0);
865 CPPInstance* pyobj =
866 (CPPInstance*)((PyTypeObject*)pyclass)->tp_new((PyTypeObject*)pyclass, args, nullptr);
867 Py_DECREF(args);
868
869// bind, register and return if successful
870 if (pyobj != 0) { // fill proxy value?
871 unsigned objflags =
872 (isRef ? CPPInstance::kIsReference : 0) | (isValue ? CPPInstance::kIsValue : 0) | (flags & CPPInstance::kIsOwner);
873 pyobj->Set(address, (CPPInstance::EFlags)objflags);
874
875 if (smart_type)
876 pyobj->SetSmart(smart_type);
877
878 // do not register null pointers, references (?), or direct usage of smart pointers or iterators
879 if (address && !isRef && !(flags & (CPPInstance::kNoWrapConv|CPPInstance::kNoMemReg)))
880 MemoryRegulator::RegisterPyObject(pyobj, pyobj->GetObject());
881 }
882
883// successful completion; wrap exception options to make them raiseable, normal return otherwise
884 if (((CPPClass*)pyclass)->fFlags & CPPScope::kIsException) {
885 PyObject* exc_obj = CPPExcInstance_Type.tp_new(&CPPExcInstance_Type, nullptr, nullptr);
886 ((CPPExcInstance*)exc_obj)->fCppInstance = (PyObject*)pyobj;
887 Py_DECREF(pyclass);
888 return exc_obj;
889 }
890
891 Py_DECREF(pyclass);
892
893 return (PyObject*)pyobj;
894}
895
896//----------------------------------------------------------------------------
898 Cppyy::TCppType_t klass, const unsigned flags)
899{
900// if the object is a null pointer, return a typed one (as needed for overloading)
901 if (!address)
902 return BindCppObjectNoCast(address, klass, flags);
903
904// only known or knowable objects will be bound
905 if (!klass) {
906 PyErr_SetString(PyExc_TypeError, "attempt to bind C++ object w/o class");
907 return nullptr;
908 }
909
910 bool isRef = flags & CPPInstance::kIsReference;
911
912// get actual class for recycling checking and/or downcasting
913 Cppyy::TCppType_t clActual = isRef ? 0 : Cppyy::GetActualClass(klass, address);
914
915// downcast to real class for object returns, unless pinned
916 if (clActual && klass != clActual) {
917 auto pci = gPinnedTypes.find(klass);
918 if (pci == gPinnedTypes.end()) {
919 intptr_t offset = Cppyy::GetBaseOffset(
920 clActual, klass, address, -1 /* down-cast */, true /* report errors */);
921 if (offset != -1) { // may fail if clActual not fully defined
922 address = (void*)((intptr_t)address + offset);
923 klass = clActual;
924 }
925 }
926 }
927
928// actual binding (returned object may be zero w/ a python exception set)
929 return BindCppObjectNoCast(address, klass, flags);
930}
931
932//----------------------------------------------------------------------------
934 Cppyy::TCppObject_t address, Cppyy::TCppType_t klass, dims_t dims)
935{
936// TODO: this function exists for symmetry; need to figure out if it's useful
937 return TupleOfInstances_New(address, klass, dims[0], dims+1);
938}
#define Py_TYPE(ob)
Definition CPyCppyy.h:217
#define CPyCppyy_PyText_InternFromString
Definition CPyCppyy.h:103
#define CPyCppyy_PyText_AsString
Definition CPyCppyy.h:97
#define CPyCppyy_PyText_AppendAndDel
Definition CPyCppyy.h:105
#define CPyCppyy_PyText_FromString
Definition CPyCppyy.h:102
Cppyy::TCppType_t fUnderlyingType
static PyClassMap_t gPyClasses
std::map< Cppyy::TCppScope_t, PyObject * > PyClassMap_t
_object PyObject
std::ios_base::fmtflags fFlags
#define c(i)
Definition RSha256.hxx:101
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h offset
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char cname
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
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t property
char name[80]
Definition TGX11.cxx:110
#define pyname
void Set(void *address, EFlags flags=kDefault)
Definition CPPInstance.h:88
void SetSmart(PyObject *smart_type)
const std::string & GetName() const
Definition CPPOverload.h:62
void AdoptTemplate(PyCallable *pc)
void AdoptMethod(PyCallable *pc)
void MergeOverload(CPPOverload *mp)
R__EXTERN PyObject * gModule
Definition TPython.cxx:104
PyObject * gSetItem
Definition PyStrings.cxx:21
std::string MapOperatorName(const std::string &name, bool bTakesParames)
Definition Utility.cxx:793
const std::string Compound(const std::string &name)
Definition Utility.cxx:848
Set of helper functions that are invoked from the pythonizors, on the Python side.
CPPOverload * CPPOverload_New(const std::string &name, std::vector< PyCallable * > &methods)
Definition CPPOverload.h:95
PyTypeObject CPPInstance_Type
PyTypeObject CPPExcInstance_Type
PyObject * GetScopeProxy(Cppyy::TCppScope_t)
static PyObject * GetAttrDirect(PyObject *pyclass, PyObject *pyname)
static PyObject * CreateNewCppProxyClass(Cppyy::TCppScope_t klass, PyObject *pybases)
bool Pythonize(PyObject *pyclass, const std::string &name)
std::set< Cppyy::TCppType_t > gPinnedTypes
PyObject * BindCppObjectNoCast(Cppyy::TCppObject_t object, Cppyy::TCppType_t klass, const unsigned flags=0)
bool CPPOverload_Check(T *object)
Definition CPPOverload.h:83
bool CPPScope_Check(T *object)
Definition CPPScope.h:76
static int BuildScopeProxyDict(Cppyy::TCppScope_t scope, PyObject *pyclass)
static void sync_templates(PyObject *pyclass, const std::string &mtCppName, const std::string &mtName)
static PyObject * BuildCppClassBases(Cppyy::TCppType_t klass)
static void AddScopeToParent(PyObject *parent, const std::string &name, PyObject *newscope)
CPPScope * CPPScopeMeta_New(Cppyy::TCppScope_t klass, PyObject *args)
Definition CPPScope.h:88
CPPDataMember * CPPDataMember_New(Cppyy::TCppScope_t scope, Cppyy::TCppIndex_t idata)
PyObject * CreateExcScopeProxy(PyObject *pyscope, PyObject *pyname, PyObject *parent)
PyObject * CreateScopeProxy(Cppyy::TCppScope_t)
static void AddPropertyToClass(PyObject *pyclass, Cppyy::TCppScope_t scope, Cppyy::TCppIndex_t idata)
R__EXTERN PyObject * gThisModule
Definition TPython.cxx:100
PyObject * BindCppObject(Cppyy::TCppObject_t object, Cppyy::TCppType_t klass, const unsigned flags=0)
PyObject * gPyTypeMap
bool TemplateProxy_Check(T *object)
TemplateProxy * TemplateProxy_New(const std::string &cppname, const std::string &pyname, PyObject *pyclass)
static void CollectUniqueBases(Cppyy::TCppType_t klass, std::deque< std::string > &uqb)
PyObject * BindCppObjectArray(Cppyy::TCppObject_t address, Cppyy::TCppType_t klass, Py_ssize_t *dims)
size_t TCppIndex_t
Definition cpp_cppyy.h:24
RPY_EXPORTED TCppIndex_t GetNumMethods(TCppScope_t scope)
RPY_EXPORTED ptrdiff_t GetBaseOffset(TCppType_t derived, TCppType_t base, TCppObject_t address, int direction, bool rerror=false)
RPY_EXPORTED bool IsEnumData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED bool IsAbstract(TCppType_t type)
intptr_t TCppMethod_t
Definition cpp_cppyy.h:22
RPY_EXPORTED bool IsTemplate(const std::string &template_name)
RPY_EXPORTED bool IsEnum(const std::string &type_name)
RPY_EXPORTED bool ExistsMethodTemplate(TCppScope_t scope, const std::string &name)
RPY_EXPORTED std::string GetMethodName(TCppMethod_t)
RPY_EXPORTED TCppScope_t gGlobalScope
Definition cpp_cppyy.h:51
RPY_EXPORTED bool IsSubtype(TCppType_t derived, TCppType_t base)
void * TCppObject_t
Definition cpp_cppyy.h:21
RPY_EXPORTED bool IsConstructor(TCppMethod_t method)
RPY_EXPORTED std::string ResolveName(const std::string &cppitem_name)
TCppScope_t TCppType_t
Definition cpp_cppyy.h:19
RPY_EXPORTED TCppIndex_t GetMethodNumArgs(TCppMethod_t)
RPY_EXPORTED TCppType_t GetActualClass(TCppType_t klass, TCppObject_t obj)
RPY_EXPORTED std::string GetBaseName(TCppType_t type, TCppIndex_t ibase)
RPY_EXPORTED bool IsNamespace(TCppScope_t scope)
RPY_EXPORTED std::string GetScopedFinalName(TCppType_t type)
RPY_EXPORTED bool IsPublicData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED bool IsComplete(const std::string &type_name)
RPY_EXPORTED bool IsStaticMethod(TCppMethod_t method)
RPY_EXPORTED bool IsStaticData(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED std::string GetDatamemberType(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED TCppMethod_t GetMethod(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED std::string GetTemplatedMethodName(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED TCppScope_t GetScope(const std::string &scope_name)
size_t TCppScope_t
Definition cpp_cppyy.h:18
RPY_EXPORTED bool IsTemplatedConstructor(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED TCppIndex_t GetNumDatamembers(TCppScope_t scope)
RPY_EXPORTED TCppIndex_t GetNumBases(TCppType_t type)
RPY_EXPORTED TCppIndex_t GetNumTemplatedMethods(TCppScope_t scope)
RPY_EXPORTED std::string GetMethodResultType(TCppMethod_t)
RPY_EXPORTED std::string GetFinalName(TCppType_t type)
RPY_EXPORTED bool IsMethodTemplate(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED std::string GetDatamemberName(TCppScope_t scope, TCppIndex_t idata)
RPY_EXPORTED bool IsPublicMethod(TCppMethod_t method)
RPY_EXPORTED intptr_t GetDatamemberOffset(TCppScope_t scope, TCppIndex_t idata)
PyObject_HEAD PyObject * dict