Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
CPPInstance.cxx
Go to the documentation of this file.
1// Bindings
2#include "CPyCppyy.h"
3#include "CPPInstance.h"
4#include "CPPScope.h"
5#include "CPPOverload.h"
6#include "MemoryRegulator.h"
7#include "ProxyWrappers.h"
8#include "PyStrings.h"
9#include "TypeManip.h"
10#include "Utility.h"
11
13
14// Standard
15#include <algorithm>
16#include <sstream>
17
18
19//- data _____________________________________________________________________
20namespace CPyCppyy {
22}
23
24//______________________________________________________________________________
25// Python-side proxy objects
26// =========================
27//
28// C++ objects are represented in Python by CPPInstances, which encapsulate
29// them using either a pointer (normal), pointer-to-pointer (kIsReference set),
30// or as an owned value (kIsValue set). Objects held as reference are never
31// owned, otherwise the object is owned if kIsOwner is set.
32//
33// In addition to encapsulation, CPPInstance offers rudimentary comparison
34// operators (based on pointer value and class comparisons); stubs (with lazy
35// lookups) for numeric operators; and a representation that prints the C++
36// pointer values, rather than the PyObject* ones as is the default.
37//
38// Smart pointers have the underlying type as the Python type, but store the
39// pointer to the smart pointer. They carry a pointer to the Python-sode smart
40// class for dereferencing to get to the actual instance pointer.
41
42
43//- private helpers ----------------------------------------------------------
44namespace {
45
46// Several specific use cases require extra data in a CPPInstance, but can not
47// be a new type. E.g. cross-inheritance derived types are by definition added
48// a posterio, and caching of datamembers is up to the datamember, not the
49// instance type. To not have normal use of CPPInstance take extra memory, this
50// extended data can slot in place of fObject for those use cases.
51
52struct ExtendedData {
53 ExtendedData() : fObject(nullptr), fSmartClass(nullptr), fDispatchPtr(nullptr), fArraySize(0) {}
55 for (auto& pc : fDatamemberCache)
56 Py_XDECREF(pc.second);
57 fDatamemberCache.clear();
58 }
59
60// the original object reference it replaces (Note: has to be first data member, see usage
61// in GetObjectRaw(), e.g. for ptr-ptr passing)
62 void* fObject;
63
64// for caching expensive-to-create data member representations
65 CPyCppyy::CI_DatamemberCache_t fDatamemberCache;
66
67// for smart pointer types
68 CPyCppyy::CPPSmartClass* fSmartClass;
69
70// for back-referencing from Python-derived instances
71 CPyCppyy::DispatchPtr* fDispatchPtr;
72
73// for representing T* as a low-level array
74 Py_ssize_t fArraySize;
75};
76
77} // unnamed namespace
78
79#define EXT_OBJECT(pyobj) ((ExtendedData*)((pyobj)->fObject))->fObject
80#define DATA_CACHE(pyobj) ((ExtendedData*)((pyobj)->fObject))->fDatamemberCache
81#define SMART_CLS(pyobj) ((ExtendedData*)((pyobj)->fObject))->fSmartClass
82#define SMART_TYPE(pyobj) SMART_CLS(pyobj)->fCppType
83#define DISPATCHPTR(pyobj) ((ExtendedData*)((pyobj)->fObject))->fDispatchPtr
84#define ARRAY_SIZE(pyobj) ((ExtendedData*)((pyobj)->fObject))->fArraySize
85
87 if (fFlags & kIsExtended)
88 return;
89 void* obj = fObject;
90 fObject = (void*)new ExtendedData{};
91 EXT_OBJECT(this) = obj;
93}
94
96{
97 if (IsSmart()) {
98 // We get the raw pointer from the smart pointer each time, in case it has
99 // changed or has been freed.
100 return Cppyy::CallR(SMART_CLS(this)->fDereferencer, EXT_OBJECT(this), 0, nullptr);
101 }
102 return EXT_OBJECT(this);
103}
104
105
106//- public methods -----------------------------------------------------------
108{
109// create a fresh instance; args and kwds are not used by op_new (see below)
110 PyObject* self = (PyObject*)this;
111 if (!target) target = Py_TYPE(self);
112 PyObject* newinst = target->tp_new(target, nullptr, nullptr);
113
114// set the C++ instance as given
115 ((CPPInstance*)newinst)->fObject = cppinst;
116
117// look for user-provided __cpp_copy__ (not reusing __copy__ b/c of differences
118// in semantics: need to pass in the new instance) ...
119 PyObject* cpy = PyObject_GetAttrString(self, (char*)"__cpp_copy__");
120 if (cpy && PyCallable_Check(cpy)) {
121 PyObject* args = PyTuple_New(1);
123 PyTuple_SET_ITEM(args, 0, newinst);
124 PyObject* res = PyObject_CallObject(cpy, args);
125 Py_DECREF(args);
126 Py_DECREF(cpy);
127 if (res) {
128 Py_DECREF(res);
129 return (CPPInstance*)newinst;
130 }
131
132 // error already set, but need to return nullptr
134 return nullptr;
135 } else if (cpy)
136 Py_DECREF(cpy);
137 else
138 PyErr_Clear();
139
140// ... otherwise, shallow copy any Python-side dictionary items
143 bool bMergeOk = PyDict_Merge(newdct, selfdct, 1) == 0;
146
147 if (!bMergeOk) {
148 // presume error already set
150 return nullptr;
151 }
152
154 return (CPPInstance*)newinst;
155}
156
157
158//----------------------------------------------------------------------------
160{
161 fFlags |= kIsOwner;
162 if ((fFlags & kIsExtended) && DISPATCHPTR(this))
163 DISPATCHPTR(this)->PythonOwns();
164}
165
166//----------------------------------------------------------------------------
168{
169 fFlags &= ~kIsOwner;
170 if ((fFlags & kIsExtended) && DISPATCHPTR(this))
171 DISPATCHPTR(this)->CppOwns();
172}
173
174//----------------------------------------------------------------------------
176{
177 CreateExtension();
180 fFlags |= kIsSmartPtr;
181}
182
183//----------------------------------------------------------------------------
185{
186 if (!IsSmart()) return (Cppyy::TCppType_t)0;
187 return SMART_TYPE(this);
188}
189
190//----------------------------------------------------------------------------
192{
193// The declared underlying type of the embedded smart pointer (e.g. 'Base' for
194// a std::unique_ptr<Base>). This is independent of any auto-down-cast applied
195// to the dereferenced object, and so is what must be used to decide whether the
196// smart pointer can be passed to a function expecting a particular smart type.
197 if (!IsSmart()) return (Cppyy::TCppType_t)0;
198 return SMART_CLS(this)->fUnderlyingType;
199}
200
201//----------------------------------------------------------------------------
203{
204// Return the cache for expensive data objects (and make extended as necessary)
205 CreateExtension();
206 return DATA_CACHE(this);
207}
208
209//----------------------------------------------------------------------------
211{
212// Set up the dispatch pointer for memory management
213 CreateExtension();
214 DISPATCHPTR(this) = (DispatchPtr*)ptr;
215}
216
217
218//----------------------------------------------------------------------------
220// Destroy the held C++ object, if owned; does not deallocate the proxy.
221
222 Cppyy::TCppType_t klass = pyobj->ObjectIsA(false /* check_smart */);
223 void*& cppobj = pyobj->GetObjectRaw();
224
225 if (pyobj->fFlags & CPPInstance::kIsRegulated)
227
228 if (cppobj && (pyobj->fFlags & CPPInstance::kIsOwner)) {
229 if (pyobj->fFlags & CPPInstance::kIsValue) {
232 } else
234 }
235 cppobj = nullptr;
236
237 if (pyobj->IsExtended()) delete (ExtendedData*)pyobj->fObject;
239}
240
241
242namespace CPyCppyy {
243
244//----------------------------------------------------------------------------
245static int op_traverse(CPPInstance* /*pyobj*/, visitproc /*visit*/, void* /*arg*/)
246{
247 return 0;
248}
249
250
251//= CPyCppyy object proxy null-ness checking =================================
253{
254// Null of the proxy is determined by null-ness of the held C++ object.
255 if (!self->GetObject())
256 return 0;
257
258// If the object is valid, then the normal Python behavior is to allow __len__
259// to determine truth. However, that function is defined in typeobject.c and only
260// installed if tp_as_number exists w/o the nb_nonzero/nb_bool slot filled in, so
261// it can not be called directly. Instead, since we're only ever dealing with
262// CPPInstance derived objects, ignore length from sequence or mapping and call
263// the __len__ method, if any, directly.
264
266 if (!pylen) {
267 PyErr_Clear();
268 return 1; // since it's still a valid object
269 }
270
273 return result;
274}
275
276//= CPyCppyy object explicit destruction =====================================
278{
279// User access to force deletion of the object. Needed in case of a true
280// garbage collector (like in PyPy), to allow the user control over when
281// the C++ destructor is called. This method requires that the C++ object
282// is owned (no-op otherwise).
285}
286
287//= CPyCppyy object dispatch support =========================================
288static PyObject* op_dispatch(PyObject* self, PyObject* args, PyObject* /* kwds */)
289{
290// User-side __dispatch__ method to allow selection of a specific overloaded
291// method. The actual selection is in the __overload__() method of CPPOverload.
292 PyObject *mname = nullptr, *sigarg = nullptr;
293 if (!PyArg_ParseTuple(args, const_cast<char*>("O!O!:__dispatch__"),
295 return nullptr;
296
297// get the named overload
299 if (!pymeth)
300 return nullptr;
301
302// get the '__overload__' method to allow overload selection
303 PyObject* pydisp = PyObject_GetAttrString(pymeth, const_cast<char*>("__overload__"));
304 if (!pydisp) {
306 return nullptr;
307 }
308
309// finally, call dispatch to get the specific overload
313 return oload;
314}
315
316//= CPyCppyy smart pointer support ===========================================
318{
319 if (!self->IsSmart()) {
320 // TODO: more likely should raise
322 }
323
325}
326
327//= pointer-as-array support for legacy C code ===============================
329{
330 CreateExtension();
331 fFlags |= kIsArray;
332 ARRAY_SIZE(this) = sz;
333}
334
336 if (!(fFlags & kIsArray))
337 return -1;
338 return (Py_ssize_t)ARRAY_SIZE(this);
339}
340
342{
343// Allow the user to fix up the actual (type-strided) size of the buffer.
344 if (!PyTuple_Check(shape) || PyTuple_GET_SIZE(shape) != 1) {
345 PyErr_SetString(PyExc_TypeError, "tuple object of size 1 expected");
346 return nullptr;
347 }
348
349 long sz = PyLong_AsLong(PyTuple_GET_ITEM(shape, 0));
350 if (sz <= 0) {
351 PyErr_SetString(PyExc_ValueError, "array length must be positive");
352 return nullptr;
353 }
354
355 self->CastToArray(sz);
356
358}
359
361{
362// In C, it is common to represent an array of structs as a pointer to the first
363// object in the array. If the caller indexes a pointer to an object that does not
364// define indexing, then highly likely such C-style indexing is the goal. Just
365// like C, this is potentially unsafe, so caveat emptor.
366
368 PyErr_Format(PyExc_TypeError, "%s object does not support indexing", Py_TYPE(self)->tp_name);
369 return nullptr;
370 }
371
372 if (idx < 0) {
373 // this is debatable, and probably should not care, but the use case is pretty
374 // circumscribed anyway, so might as well keep the functionality simple
375 PyErr_SetString(PyExc_IndexError, "negative indices not supported for array of structs");
376 return nullptr;
377 }
378
379 if (self->fFlags & CPPInstance::kIsArray) {
381 if (0 <= maxidx && maxidx <= idx) {
382 PyErr_SetString(PyExc_IndexError, "index out of range");
383 return nullptr;
384 }
385 }
386
387 unsigned flags = 0; size_t sz = sizeof(void*);
388 if (self->fFlags & CPPInstance::kIsPtrPtr) {
390 } else {
391 sz = Cppyy::SizeOf(((CPPClass*)Py_TYPE(self))->fCppType);
392 }
393
394 uintptr_t address = (uintptr_t)(flags ? self->GetObjectRaw() : self->GetObject());
395 void* indexed_obj = (void*)(address+(uintptr_t)(idx*sz));
396
397 return BindCppObjectNoCast(indexed_obj, ((CPPClass*)Py_TYPE(self))->fCppType, flags);
398}
399
400//- sequence methods --------------------------------------------------------
402 0, // sq_length
403 0, // sq_concat
404 0, // sq_repeat
405 (ssizeargfunc)op_item, // sq_item
406 0, // sq_slice
407 0, // sq_ass_item
408 0, // sq_ass_slice
409 0, // sq_contains
410 0, // sq_inplace_concat
411 0, // sq_inplace_repeat
412};
413
415 static PyCFunction reducer = nullptr;
416 return reducer;
417}
418
420{
422 if (!reducer) {
424 return nullptr;
425 }
426 return reducer(self, args);
427}
428
429
430//----------------------------------------------------------------------------
432 {(char*)"__destruct__", (PyCFunction)op_destruct, METH_NOARGS,
433 (char*)"call the C++ destructor"},
434 {(char*)"__dispatch__", (PyCFunction)op_dispatch, METH_VARARGS,
435 (char*)"dispatch to selected overload"},
436 {(char*)"__smartptr__", (PyCFunction)op_get_smartptr, METH_NOARGS,
437 (char*)"get associated smart pointer, if any"},
438 {(char*)"__reduce__", (PyCFunction)op_reduce, METH_NOARGS,
439 (char*)"reduce method for serialization"},
440 {(char*)"__reshape__", (PyCFunction)op_reshape, METH_O,
441 (char*)"cast pointer to 1D array type"},
442 {(char*)nullptr, nullptr, 0, nullptr}
443};
444
445
446//= CPyCppyy object proxy construction/destruction ===========================
448{
449// Create a new object proxy (holder only).
450 CPPInstance* pyobj = (CPPInstance*)subtype->tp_alloc(subtype, 0);
451 pyobj->fObject = nullptr;
453
454 return pyobj;
455}
456
457//----------------------------------------------------------------------------
459{
460// Remove (Python-side) memory held by the object proxy.
464}
465
466//----------------------------------------------------------------------------
468{
469// Garbage collector clear of held python member objects; this is a good time
470// to safely remove this object from the memory regulator.
471 if (pyobj->fFlags & CPPInstance::kIsRegulated)
473
474 return 0;
475}
476
477//----------------------------------------------------------------------------
479{
480 using namespace Utility;
481
482// special case for C++11 style nullptr
483 if (obj == gNullPtrObject) {
484 void* rawcpp = ((CPPInstance*)self)->GetObjectRaw();
485 switch (op) {
486 case Py_EQ:
487 if (rawcpp == nullptr) Py_RETURN_TRUE;
489 case Py_NE:
490 if (rawcpp != nullptr) Py_RETURN_TRUE;
492 default:
493 return nullptr; // not implemented
494 }
495 }
496
497 if (!klass->fOperators)
498 klass->fOperators = new PyOperators{};
499
500 bool flipit = false;
501 PyObject* binop = op == Py_EQ ? klass->fOperators->fEq : klass->fOperators->fNe;
502 if (!binop) {
503 const char* cppop = op == Py_EQ ? "==" : "!=";
504 PyCallable* pyfunc = FindBinaryOperator(self, obj, cppop);
506 else {
508 binop = Py_None;
509 }
510 // sets the operator to Py_None if not found, indicating that search was done
511 if (op == Py_EQ) klass->fOperators->fEq = binop;
512 else klass->fOperators->fNe = binop;
513 }
514
515 if (binop == Py_None) { // can try !== or !!= as alternatives
516 binop = op == Py_EQ ? klass->fOperators->fNe : klass->fOperators->fEq;
517 if (binop && binop != Py_None) flipit = true;
518 }
519
520 if (!binop || binop == Py_None) return nullptr;
521
522 PyObject* args = PyTuple_New(1);
523 Py_INCREF(obj); PyTuple_SET_ITEM(args, 0, obj);
524// since this overload is "ours", don't have to worry about rebinding
525 ((CPPOverload*)binop)->fSelf = (CPPInstance*)self;
526 PyObject* result = CPPOverload_Type.tp_call(binop, args, nullptr);
527 ((CPPOverload*)binop)->fSelf = nullptr;
528 Py_DECREF(args);
529
530 if (!result) {
531 PyErr_Clear();
532 return nullptr;
533 }
534
535// successful result, but may need to reverse the outcome
536 if (!flipit) return result;
537
540 if (istrue) {
542 }
544}
545
546static inline void* cast_actual(void* obj) {
547 void* address = ((CPPInstance*)obj)->GetObject();
549 return address;
550
551 Cppyy::TCppType_t klass = ((CPPClass*)Py_TYPE((PyObject*)obj))->fCppType;
553 if (clActual && clActual != klass) {
554 intptr_t offset = Cppyy::GetBaseOffset(
555 clActual, klass, address, -1 /* down-cast */, true /* report errors */);
556 if (offset != -1) address = (void*)((intptr_t)address + offset);
557 }
558
559 return address;
560}
561
562
563#define CPYCPPYY_ORDERED_OPERATOR_STUB(op, ometh, label) \
564 if (!ometh) { \
565 PyCallable* pyfunc = Utility::FindBinaryOperator((PyObject*)self, other, #op);\
566 if (pyfunc) \
567 ometh = (PyObject*)CPPOverload_New(#label, pyfunc); \
568 } \
569 meth = ometh;
570
572{
573// Rich set of comparison objects; currently supported:
574// == : Py_EQ
575// != : Py_NE
576//
577// < : Py_LT
578// <= : Py_LE
579// > : Py_GT
580// >= : Py_GE
581//
582
583// associative comparison operators
584 if (op == Py_EQ || op == Py_NE) {
585 // special case for None to compare True to a null-pointer
586 if ((PyObject*)other == Py_None && !self->fObject) {
587 const char *msg =
588 "\nComparison of C++ nullptr objects with `None` is no longer supported."
589 "\n\nPreviously, `None` was treated as equivalent to a null C++ pointer, "
590 "but this led to confusing behavior where `x == None` could be True even though `x is None` was False."
591 "\n\nTo test whether a C++ object is null or not, check its truth value instead:"
592 "\n if not x: ..."
593 "\nor use `x is None` to explicitly check for Python None."
594 "\n";
595
597 return NULL; // stop execution, raise TypeError
598 }
599
600 // use C++-side operators if available
604 if (result) return result;
605
606 // default behavior: type + held pointer value defines identity; if both are
607 // CPPInstance objects, perform an additional autocast if need be
608 bool bIsEq = false;
609
610 if ((Py_TYPE(self) == Py_TYPE(other) && \
611 self->GetObject() == ((CPPInstance*)other)->GetObject())) {
612 // direct match
613 bIsEq = true;
614 } else if (CPPInstance_Check(other)) {
615 // try auto-cast match
616 void* addr1 = cast_actual(self);
617 void* addr2 = cast_actual(other);
618 bIsEq = addr1 && addr2 && (addr1 == addr2);
619 }
620
621 if ((op == Py_EQ && bIsEq) || (op == Py_NE && !bIsEq))
623
625 }
626
627// ordered comparison operators
628 else if (op == Py_LT || op == Py_LE || op == Py_GT || op == Py_GE) {
630 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};
631 PyObject* meth = nullptr;
632
633 switch (op) {
634 case Py_LT:
635 CPYCPPYY_ORDERED_OPERATOR_STUB(<, klass->fOperators->fLt, __lt__)
636 break;
637 case Py_LE:
638 CPYCPPYY_ORDERED_OPERATOR_STUB(<=, klass->fOperators->fLe, __le__)
639 break;
640 case Py_GT:
641 CPYCPPYY_ORDERED_OPERATOR_STUB(>, klass->fOperators->fGt, __gt__)
642 break;
643 case Py_GE:
644 CPYCPPYY_ORDERED_OPERATOR_STUB(>=, klass->fOperators->fGe, __ge__)
645 break;
646 }
647
648 if (!meth) {
650 return nullptr;
651 }
652
654 }
655
657 return Py_NotImplemented;
658}
659
660//----------------------------------------------------------------------------
662{
663// Build a representation string of the object proxy that shows the address
664// of the C++ object that is held, as well as its type.
667 return PyBaseObject_Type.tp_repr((PyObject*)self);
669
670 Cppyy::TCppType_t klass = self->ObjectIsA();
671 std::string clName = klass ? Cppyy::GetFinalName(klass) : "<unknown>";
672 if (self->fFlags & CPPInstance::kIsPtrPtr)
673 clName.append("**");
674 else if (self->fFlags & CPPInstance::kIsReference)
675 clName.append("*");
676
677 PyObject* repr = nullptr;
678 if (self->IsSmart()) {
681 const_cast<char*>("<%s.%s object at %p held by %s at %p>"),
683 self->GetObject(), smartPtrName.c_str(), self->GetObjectRaw());
684 } else {
685 repr = CPyCppyy_PyText_FromFormat(const_cast<char*>("<%s.%s object at %p>"),
686 CPyCppyy_PyText_AsString(modname), clName.c_str(), self->GetObject());
687 }
688
690 return repr;
691}
692
693//----------------------------------------------------------------------------
695{
696// Cannot use PyLong_AsSize_t here, as it cuts of at PY_SSIZE_T_MAX, which is
697// only half of the max of std::size_t returned by the hash.
698 if (sizeof(unsigned long) >= sizeof(size_t))
699 return (Py_hash_t)PyLong_AsUnsignedLong(obj);
701}
702
704{
705// Try to locate an std::hash for this type and use that if it exists
707 if (klass->fOperators && klass->fOperators->fHash) {
708 Py_hash_t h = 0;
709 PyObject* hashval = PyObject_CallFunctionObjArgs(klass->fOperators->fHash, (PyObject*)self, nullptr);
710 if (hashval) {
713 }
714 return h;
715 }
716
718 if (stdhash) {
721 bool isValid = PyMapping_HasKeyString(dct, (char*)"__call__");
722 Py_DECREF(dct);
723 if (isValid) {
725 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};
726 klass->fOperators->fHash = hashobj;
728
729 Py_hash_t h = 0;
731 if (hashval) {
734 }
735 return h;
736 }
738 }
739
740// if not valid, simply reset the hash function so as to not kill performance
742 return PyBaseObject_Type.tp_hash((PyObject*)self);
743}
744
745//----------------------------------------------------------------------------
747{
748 static Cppyy::TCppScope_t sOStringStreamID = Cppyy::GetScope("std::ostringstream");
749 std::ostringstream s;
751 Py_INCREF(pys);
752#if PY_VERSION_HEX >= 0x03000000
753// for py3 and later, a ref-count of 2 is okay to consider the object temporary, but
754// in this case, we can't lose our existing ostrinstring (otherwise, we'd have to peel
755// it out of the return value, if moves are used
756 Py_INCREF(pys);
757#endif
758
759 PyObject* res;
762
763 Py_DECREF(pys);
764#if PY_VERSION_HEX >= 0x03000000
765 Py_DECREF(pys);
766#endif
767
768 if (res) {
769 Py_DECREF(res);
770 return CPyCppyy_PyText_FromString(s.str().c_str());
771 }
772
773 return nullptr;
774}
775
776
778 return ((CPPScope*)Py_TYPE((PyObject*)self))->fFlags & flag;
779}
780
782 ((CPPScope*)Py_TYPE((PyObject*)self))->fFlags |= flag;
783}
784
786{
787// There are three possible options here:
788// 1. Available operator<< to convert through an ostringstream
789// 2. Cling's pretty printing
790// 3. Generic printing as done in op_repr
791//
792// Additionally, there may be a mapped __str__ from the C++ type defining `operator char*`
793// or `operator const char*`. Results are memoized for performance reasons.
794
795// 0. Protect against trying to print a typed nullptr object through an insertion operator
796 if (!self->GetObject())
797 return op_repr(self);
798
799// 1. Available operator<< to convert through an ostringstream
803 continue;
804
805 else if (pyname == (PyObject*)0x01) {
806 // normal lookup failed; attempt lazy install of global operator<<(ostream&, type&)
807 std::string rcname = Utility::ClassName((PyObject*)self);
809 PyCallable* pyfunc = Utility::FindBinaryOperator("std::ostream", rcname, "<<", rnsID);
810 if (!pyfunc)
811 continue;
812
814
817
818 } else if (pyname == (PyObject*)0x02) {
819 // TODO: the only reason this still exists, is b/c friend functions are otherwise not found
820 // TODO: ToString() still leaks ...
821 const std::string& pretty = Cppyy::ToString(self->ObjectIsA(), self->GetObject());
822 if (!pretty.empty())
823 return CPyCppyy_PyText_FromString(pretty.c_str());
824 continue;
825 }
826
829
830 if (lshift) {
833 if (result)
834 return result;
835 }
836
837 PyErr_Clear();
838 }
839
840 // failed ostream printing; don't try again
842 }
843
844// 2. Cling's pretty printing (not done through backend for performance reasons)
846 static PyObject* printValue = nullptr;
847 if (!printValue) {
848 PyObject* gbl = PyDict_GetItemString(PySys_GetObject((char*)"modules"), "cppyy.gbl");
849 PyObject* cl = PyObject_GetAttrString(gbl, (char*)"cling");
850 printValue = PyObject_GetAttrString(cl, (char*)"printValue");
851 Py_DECREF(cl);
852 // gbl is borrowed
853 if (printValue) {
854 Py_DECREF(printValue); // make borrowed
855 if (!PyCallable_Check(printValue))
856 printValue = nullptr; // unusable ...
857 }
858 if (!printValue) // unlikely
860 }
861
862 if (printValue) {
863 // as printValue only works well for templates taking pointer arguments, we'll
864 // have to force the issue by working with a by-ptr object
865 Cppyy::TCppObject_t cppobj = self->GetObjectRaw();
867 if (!(self->fFlags & CPPInstance::kIsReference)) {
870 } else {
872 }
873
874 // explicit template lookup
876 PyObject* OL = PyObject_GetItem(printValue, clName);
878
879 PyObject* pretty = OL ? PyObject_CallFunctionObjArgs(OL, byref, nullptr) : nullptr;
880 Py_XDECREF(OL);
882
883 PyObject* result = nullptr;
884 if (pretty) {
885 const std::string& pv = *(std::string*)((CPPInstance*)pretty)->GetObject();
886 if (!pv.empty() && pv.find("@0x") == std::string::npos)
889 if (result) return result;
890 }
891
892 PyErr_Clear();
893 }
894
895 // if not available/specialized, don't try again
897 }
898
899// 3. Generic printing as done in op_repr
900 return op_repr(self);
901}
902
903//-----------------------------------------------------------------------------
905{
906 return PyBool_FromLong((long)(pyobj->fFlags & CPPInstance::kIsOwner));
907}
908
909//-----------------------------------------------------------------------------
911{
912// Set the ownership (True is python-owns) for the given object.
914 if (shouldown == -1 && PyErr_Occurred()) {
915 PyErr_SetString(PyExc_ValueError, "__python_owns__ should be either True or False");
916 return -1;
917 }
918
919 (bool)shouldown ? pyobj->PythonOwns() : pyobj->CppOwns();
920
921 return 0;
922}
923
924
925//-----------------------------------------------------------------------------
927 {(char*)"__python_owns__", (getter)op_getownership, (setter)op_setownership,
928 (char*)"If true, python manages the life time of this object", nullptr},
929 {(char*)nullptr, nullptr, nullptr, nullptr, nullptr}
930};
931
932
933//= CPyCppyy type number stubs to allow dynamic overrides =====================
934#define CPYCPPYY_STUB_BODY(name, op) \
935 bool previously_resolved_overload = (bool)meth; \
936 if (!meth) { \
937 PyErr_Clear(); \
938 PyCallable* pyfunc = Utility::FindBinaryOperator(left, right, #op); \
939 if (pyfunc) meth = (PyObject*)CPPOverload_New(#name, pyfunc); \
940 else { \
941 PyErr_SetString(PyExc_NotImplementedError, ""); \
942 return nullptr; \
943 } \
944 } \
945 PyObject* res = PyObject_CallFunctionObjArgs(meth, cppobj, other, nullptr);\
946 if (!res && previously_resolved_overload) { \
947 /* try again, in case (left, right) are different types than before */ \
948 PyErr_Clear(); \
949 PyCallable* pyfunc = Utility::FindBinaryOperator(left, right, #op); \
950 if (pyfunc) ((CPPOverload*&)meth)->AdoptMethod(pyfunc); \
951 else { \
952 PyErr_SetString(PyExc_NotImplementedError, ""); \
953 return nullptr; \
954 } \
955 /* use same overload with newly added function */ \
956 res = PyObject_CallFunctionObjArgs(meth, cppobj, other, nullptr); \
957 } \
958 return res;
959
960
961#define CPYCPPYY_OPERATOR_STUB(name, op, ometh) \
962static PyObject* op_##name##_stub(PyObject* left, PyObject* right) \
963{ \
964/* placeholder to lazily install and forward to 'ometh' if available */ \
965 CPPClass* klass = (CPPClass*)Py_TYPE(left); \
966 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{}; \
967 PyObject*& meth = ometh; \
968 PyObject *cppobj = left, *other = right; \
969 CPYCPPYY_STUB_BODY(name, op) \
970}
971
972#define CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(name, op, lmeth, rmeth) \
973static PyObject* op_##name##_stub(PyObject* left, PyObject* right) \
974{ \
975/* placeholder to lazily install and forward do '(l/r)meth' if available */ \
976 CPPClass* klass; PyObject** pmeth; \
977 PyObject *cppobj, *other; \
978 if (CPPInstance_Check(left)) { \
979 klass = (CPPClass*)Py_TYPE(left); \
980 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};\
981 pmeth = &lmeth; cppobj = left; other = right; \
982 } else if (CPPInstance_Check(right)) { \
983 klass = (CPPClass*)Py_TYPE(right); \
984 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};\
985 pmeth = &rmeth; cppobj = right; other = left; \
986 } else { \
987 PyErr_SetString(PyExc_NotImplementedError, ""); \
988 return nullptr; \
989 } \
990 PyObject*& meth = *pmeth; \
991 CPYCPPYY_STUB_BODY(name, op) \
992}
993
994#define CPYCPPYY_UNARY_OPERATOR(name, op, label) \
995static PyObject* op_##name##_stub(PyObject* pyobj) \
996{ \
997/* placeholder to lazily install unary operators */ \
998 PyCallable* pyfunc = Utility::FindUnaryOperator((PyObject*)Py_TYPE(pyobj), #op);\
999 if (pyfunc && Utility::AddToClass((PyObject*)Py_TYPE(pyobj), #label, pyfunc))\
1000 return PyObject_CallMethod(pyobj, (char*)#label, nullptr); \
1001 PyErr_SetString(PyExc_NotImplementedError, ""); \
1002 return nullptr; \
1003}
1004
1005CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(add, +, klass->fOperators->fLAdd, klass->fOperators->fRAdd)
1006CPYCPPYY_OPERATOR_STUB( sub, -, klass->fOperators->fSub)
1007CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(mul, *, klass->fOperators->fLMul, klass->fOperators->fRMul)
1008CPYCPPYY_OPERATOR_STUB( div, /, klass->fOperators->fDiv)
1012
1013//-----------------------------------------------------------------------------
1015 (binaryfunc)op_add_stub, // nb_add
1016 (binaryfunc)op_sub_stub, // nb_subtract
1017 (binaryfunc)op_mul_stub, // nb_multiply
1018#if PY_VERSION_HEX < 0x03000000
1019 (binaryfunc)op_div_stub, // nb_divide
1020#endif
1021 0, // nb_remainder
1022 0, // nb_divmod
1023 0, // nb_power
1024 (unaryfunc)op_neg_stub, // nb_negative
1025 (unaryfunc)op_pos_stub, // nb_positive
1026 0, // nb_absolute
1027 (inquiry)op_nonzero, // nb_bool (nb_nonzero in p2)
1028 (unaryfunc)op_invert_stub, // nb_invert
1029 0, // nb_lshift
1030 0, // nb_rshift
1031 0, // nb_and
1032 0, // nb_xor
1033 0, // nb_or
1034#if PY_VERSION_HEX < 0x03000000
1035 0, // nb_coerce
1036#endif
1037 0, // nb_int
1038 0, // nb_long (nb_reserved in p3)
1039 0, // nb_float
1040#if PY_VERSION_HEX < 0x03000000
1041 0, // nb_oct
1042 0, // nb_hex
1043#endif
1044 0, // nb_inplace_add
1045 0, // nb_inplace_subtract
1046 0, // nb_inplace_multiply
1047#if PY_VERSION_HEX < 0x03000000
1048 0, // nb_inplace_divide
1049#endif
1050 0, // nb_inplace_remainder
1051 0, // nb_inplace_power
1052 0, // nb_inplace_lshift
1053 0, // nb_inplace_rshift
1054 0, // nb_inplace_and
1055 0, // nb_inplace_xor
1056 0 // nb_inplace_or
1057#if PY_VERSION_HEX >= 0x02020000
1058 , 0 // nb_floor_divide
1059#if PY_VERSION_HEX < 0x03000000
1060 , 0 // nb_true_divide
1061#else
1062 , (binaryfunc)op_div_stub // nb_true_divide
1063#endif
1064 , 0 // nb_inplace_floor_divide
1065 , 0 // nb_inplace_true_divide
1066#endif
1067#if PY_VERSION_HEX >= 0x02050000
1068 , 0 // nb_index
1069#endif
1070#if PY_VERSION_HEX >= 0x03050000
1071 , 0 // nb_matrix_multiply
1072 , 0 // nb_inplace_matrix_multiply
1073#endif
1074};
1075
1076
1077//= CPyCppyy object proxy type ===============================================
1080 (char*)"cppyy.CPPInstance", // tp_name
1081 sizeof(CPPInstance), // tp_basicsize
1082 0, // tp_itemsize
1083 (destructor)op_dealloc, // tp_dealloc
1084 0, // tp_vectorcall_offset / tp_print
1085 0, // tp_getattr
1086 0, // tp_setattr
1087 0, // tp_as_async / tp_compare
1088 (reprfunc)op_repr, // tp_repr
1089 &op_as_number, // tp_as_number
1090 &op_as_sequence, // tp_as_sequence
1091 0, // tp_as_mapping
1092 (hashfunc)op_hash, // tp_hash
1093 0, // tp_call
1094 (reprfunc)op_str, // tp_str
1095 0, // tp_getattro
1096 0, // tp_setattro
1097 0, // tp_as_buffer
1101 Py_TPFLAGS_HAVE_GC, // tp_flags
1102 (char*)"cppyy object proxy (internal)", // tp_doc
1103 (traverseproc)op_traverse, // tp_traverse
1104 (inquiry)op_clear, // tp_clear
1105 (richcmpfunc)op_richcompare, // tp_richcompare
1106 0, // tp_weaklistoffset
1107 0, // tp_iter
1108 0, // tp_iternext
1109 op_methods, // tp_methods
1110 0, // tp_members
1111 op_getset, // tp_getset
1112 0, // tp_base
1113 0, // tp_dict
1114 0, // tp_descr_get
1115 0, // tp_descr_set
1116 0, // tp_dictoffset
1117 0, // tp_init
1118 0, // tp_alloc
1119 (newfunc)op_new, // tp_new
1120 0, // tp_free
1121 0, // tp_is_gc
1122 0, // tp_bases
1123 0, // tp_mro
1124 0, // tp_cache
1125 0, // tp_subclasses
1126 0 // tp_weaklist
1127#if PY_VERSION_HEX >= 0x02030000
1128 , 0 // tp_del
1129#endif
1130#if PY_VERSION_HEX >= 0x02060000
1131 , 0 // tp_version_tag
1132#endif
1133#if PY_VERSION_HEX >= 0x03040000
1134 , 0 // tp_finalize
1135#endif
1136#if PY_VERSION_HEX >= 0x03080000
1137 , 0 // tp_vectorcall
1138#endif
1140};
1141
1142} // namespace CPyCppyy
#define SMART_CLS(pyobj)
#define CPYCPPYY_UNARY_OPERATOR(name, op, label)
#define EXT_OBJECT(pyobj)
#define SMART_TYPE(pyobj)
#define CPYCPPYY_OPERATOR_STUB(name, op, ometh)
#define DATA_CACHE(pyobj)
#define DISPATCHPTR(pyobj)
#define CPYCPPYY_ORDERED_OPERATOR_STUB(op, ometh, label)
#define CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(name, op, lmeth, rmeth)
#define Py_TYPE(ob)
Definition CPyCppyy.h:196
#define Py_RETURN_TRUE
Definition CPyCppyy.h:272
#define Py_RETURN_FALSE
Definition CPyCppyy.h:276
int Py_ssize_t
Definition CPyCppyy.h:215
#define CPyCppyy_PyText_AsString
Definition CPyCppyy.h:76
#define CPYCPPYY_PYTYPE_TAIL
Definition CPyCppyy.h:412
long Py_hash_t
Definition CPyCppyy.h:114
#define ssizeargfunc
Definition CPyCppyy.h:225
#define PyBool_FromLong
Definition CPyCppyy.h:251
#define CPyCppyy_PyText_FromFormat
Definition CPyCppyy.h:80
#define Py_RETURN_NONE
Definition CPyCppyy.h:268
#define CPyCppyy_PyText_Type
Definition CPyCppyy.h:94
#define CPyCppyy_PyText_FromString
Definition CPyCppyy.h:81
#define PyVarObject_HEAD_INIT(type, size)
Definition CPyCppyy.h:194
uint32_t fFlags
_object PyObject
#define h(i)
Definition RSha256.hxx:106
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
@ kIsArray
Definition TDictionary.h:79
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 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 target
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 result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
#define ARRAY_SIZE(array)
Definition civetweb.c:510
Cppyy::TCppType_t GetSmartIsA() const
void CastToArray(Py_ssize_t sz)
CPPInstance * Copy(void *cppinst, PyTypeObject *target=nullptr)
CI_DatamemberCache_t & GetDatamemberCache()
void SetSmart(PyObject *smart_type)
PyObject_HEAD void * fObject
Definition CPPInstance.h:50
static PyCFunction & ReduceMethod()
Cppyy::TCppType_t GetSmartUnderlyingType() const
void SetDispatchPtr(void *)
static bool RegisterPyObject(CPPInstance *pyobj, void *cppobj)
static bool UnregisterPyObject(CPPInstance *pyobj, PyObject *pyclass)
PyObject * gLShiftC
Definition PyStrings.cxx:51
std::string extract_namespace(const std::string &name)
PyCallable * FindBinaryOperator(PyObject *left, PyObject *right, const char *op, Cppyy::TCppScope_t scope=0)
Definition Utility.cxx:297
bool AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Definition Utility.cxx:185
std::string ClassName(PyObject *pyobj)
Definition Utility.cxx:1107
CPPOverload * CPPOverload_New(const std::string &name, std::vector< PyCallable * > &methods)
PyTypeObject CPPInstance_Type
static PyObject * op_str_internal(PyObject *pyobj, PyObject *lshift, bool isBound)
PyObject * op_reduce(PyObject *self, PyObject *args)
static PyObject * op_div_stub(PyObject *left, PyObject *right)
static void ScopeFlagSet(CPPInstance *self, CPPScope::EFlags flag)
static Py_hash_t CPyCppyy_PyLong_AsHash_t(PyObject *obj)
PyObject * CreateScopeProxy(Cppyy::TCppScope_t, const unsigned flags=0)
static int op_nonzero(CPPInstance *self)
static PyObject * op_mul_stub(PyObject *left, PyObject *right)
static PySequenceMethods op_as_sequence
static PyMethodDef op_methods[]
static PyObject * op_repr(CPPInstance *self)
static PyObject * op_item(CPPInstance *self, Py_ssize_t idx)
PyObject * BindCppObjectNoCast(Cppyy::TCppObject_t object, Cppyy::TCppType_t klass, const unsigned flags=0)
static PyObject * op_richcompare(CPPInstance *self, PyObject *other, int op)
std::vector< std::pair< ptrdiff_t, PyObject * > > CI_DatamemberCache_t
Definition CPPInstance.h:26
static int op_setownership(CPPInstance *pyobj, PyObject *value, void *)
bool CPPScope_Check(T *object)
Definition CPPScope.h:81
static PyObject * eqneq_binop(CPPClass *klass, PyObject *self, PyObject *obj, int op)
static PyObject * op_getownership(CPPInstance *pyobj, void *)
static PyObject * op_neg_stub(PyObject *pyobj)
static int op_clear(CPPInstance *pyobj)
static PyObject * op_sub_stub(PyObject *left, PyObject *right)
void op_dealloc_nofree(CPPInstance *)
bool CPPInstance_Check(T *object)
static PyObject * op_reshape(CPPInstance *self, PyObject *shape)
static PyGetSetDef op_getset[]
PyObject * gNullPtrObject
PyTypeObject CPPOverload_Type
static PyNumberMethods op_as_number
static void * cast_actual(void *obj)
static PyObject * op_str(CPPInstance *self)
static void op_dealloc(CPPInstance *pyobj)
static PyObject * op_pos_stub(PyObject *pyobj)
static PyObject * op_add_stub(PyObject *left, PyObject *right)
static Py_hash_t op_hash(CPPInstance *self)
static PyObject * op_dispatch(PyObject *self, PyObject *args, PyObject *)
static PyObject * op_invert_stub(PyObject *pyobj)
PyTypeObject CPPScope_Type
Definition CPPScope.cxx:646
static bool ScopeFlagCheck(CPPInstance *self, CPPScope::EFlags flag)
static PyObject * op_get_smartptr(CPPInstance *self)
static CPPInstance * op_new(PyTypeObject *subtype, PyObject *, PyObject *)
static int op_traverse(CPPInstance *, visitproc, void *)
static PyObject * op_destruct(CPPInstance *self)
RPY_EXPORTED ptrdiff_t GetBaseOffset(TCppType_t derived, TCppType_t base, TCppObject_t address, int direction, bool rerror=false)
RPY_EXPORTED size_t SizeOf(TCppType_t klass)
RPY_EXPORTED std::string ToString(TCppType_t klass, TCppObject_t obj)
RPY_EXPORTED void CallDestructor(TCppType_t type, TCppObject_t self)
void * TCppObject_t
Definition cpp_cppyy.h:37
RPY_EXPORTED void Destruct(TCppType_t type, TCppObject_t instance)
TCppScope_t TCppType_t
Definition cpp_cppyy.h:35
RPY_EXPORTED TCppType_t GetActualClass(TCppType_t klass, TCppObject_t obj)
RPY_EXPORTED std::string GetScopedFinalName(TCppType_t type)
RPY_EXPORTED void Deallocate(TCppType_t type, TCppObject_t instance)
RPY_EXPORTED void * CallR(TCppMethod_t method, TCppObject_t self, size_t nargs, void *args)
RPY_EXPORTED TCppScope_t GetScope(const std::string &scope_name)
size_t TCppScope_t
Definition cpp_cppyy.h:34
RPY_EXPORTED std::string GetFinalName(TCppType_t type)