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// Return the cache for expensive data objects (and make extended as necessary)
194 CreateExtension();
195 return DATA_CACHE(this);
196}
197
198//----------------------------------------------------------------------------
200{
201// Set up the dispatch pointer for memory management
202 CreateExtension();
203 DISPATCHPTR(this) = (DispatchPtr*)ptr;
204}
205
206
207//----------------------------------------------------------------------------
209// Destroy the held C++ object, if owned; does not deallocate the proxy.
210
211 Cppyy::TCppType_t klass = pyobj->ObjectIsA(false /* check_smart */);
212 void*& cppobj = pyobj->GetObjectRaw();
213
214 if (pyobj->fFlags & CPPInstance::kIsRegulated)
216
217 if (cppobj && (pyobj->fFlags & CPPInstance::kIsOwner)) {
218 if (pyobj->fFlags & CPPInstance::kIsValue) {
221 } else
223 }
224 cppobj = nullptr;
225
226 if (pyobj->IsExtended()) delete (ExtendedData*)pyobj->fObject;
228}
229
230
231namespace CPyCppyy {
232
233//----------------------------------------------------------------------------
234static int op_traverse(CPPInstance* /*pyobj*/, visitproc /*visit*/, void* /*arg*/)
235{
236 return 0;
237}
238
239
240//= CPyCppyy object proxy null-ness checking =================================
242{
243// Null of the proxy is determined by null-ness of the held C++ object.
244 if (!self->GetObject())
245 return 0;
246
247// If the object is valid, then the normal Python behavior is to allow __len__
248// to determine truth. However, that function is defined in typeobject.c and only
249// installed if tp_as_number exists w/o the nb_nonzero/nb_bool slot filled in, so
250// it can not be called directly. Instead, since we're only ever dealing with
251// CPPInstance derived objects, ignore length from sequence or mapping and call
252// the __len__ method, if any, directly.
253
255 if (!pylen) {
256 PyErr_Clear();
257 return 1; // since it's still a valid object
258 }
259
262 return result;
263}
264
265//= CPyCppyy object explicit destruction =====================================
267{
268// User access to force deletion of the object. Needed in case of a true
269// garbage collector (like in PyPy), to allow the user control over when
270// the C++ destructor is called. This method requires that the C++ object
271// is owned (no-op otherwise).
274}
275
276//= CPyCppyy object dispatch support =========================================
277static PyObject* op_dispatch(PyObject* self, PyObject* args, PyObject* /* kwds */)
278{
279// User-side __dispatch__ method to allow selection of a specific overloaded
280// method. The actual selection is in the __overload__() method of CPPOverload.
281 PyObject *mname = nullptr, *sigarg = nullptr;
282 if (!PyArg_ParseTuple(args, const_cast<char*>("O!O!:__dispatch__"),
284 return nullptr;
285
286// get the named overload
288 if (!pymeth)
289 return nullptr;
290
291// get the '__overload__' method to allow overload selection
292 PyObject* pydisp = PyObject_GetAttrString(pymeth, const_cast<char*>("__overload__"));
293 if (!pydisp) {
295 return nullptr;
296 }
297
298// finally, call dispatch to get the specific overload
302 return oload;
303}
304
305//= CPyCppyy smart pointer support ===========================================
307{
308 if (!self->IsSmart()) {
309 // TODO: more likely should raise
311 }
312
314}
315
316//= pointer-as-array support for legacy C code ===============================
318{
319 CreateExtension();
320 fFlags |= kIsArray;
321 ARRAY_SIZE(this) = sz;
322}
323
325 if (!(fFlags & kIsArray))
326 return -1;
327 return (Py_ssize_t)ARRAY_SIZE(this);
328}
329
331{
332// Allow the user to fix up the actual (type-strided) size of the buffer.
333 if (!PyTuple_Check(shape) || PyTuple_GET_SIZE(shape) != 1) {
334 PyErr_SetString(PyExc_TypeError, "tuple object of size 1 expected");
335 return nullptr;
336 }
337
338 long sz = PyLong_AsLong(PyTuple_GET_ITEM(shape, 0));
339 if (sz <= 0) {
340 PyErr_SetString(PyExc_ValueError, "array length must be positive");
341 return nullptr;
342 }
343
344 self->CastToArray(sz);
345
347}
348
350{
351// In C, it is common to represent an array of structs as a pointer to the first
352// object in the array. If the caller indexes a pointer to an object that does not
353// define indexing, then highly likely such C-style indexing is the goal. Just
354// like C, this is potentially unsafe, so caveat emptor.
355
357 PyErr_Format(PyExc_TypeError, "%s object does not support indexing", Py_TYPE(self)->tp_name);
358 return nullptr;
359 }
360
361 if (idx < 0) {
362 // this is debatable, and probably should not care, but the use case is pretty
363 // circumscribed anyway, so might as well keep the functionality simple
364 PyErr_SetString(PyExc_IndexError, "negative indices not supported for array of structs");
365 return nullptr;
366 }
367
368 if (self->fFlags & CPPInstance::kIsArray) {
370 if (0 <= maxidx && maxidx <= idx) {
371 PyErr_SetString(PyExc_IndexError, "index out of range");
372 return nullptr;
373 }
374 }
375
376 unsigned flags = 0; size_t sz = sizeof(void*);
377 if (self->fFlags & CPPInstance::kIsPtrPtr) {
379 } else {
380 sz = Cppyy::SizeOf(((CPPClass*)Py_TYPE(self))->fCppType);
381 }
382
383 uintptr_t address = (uintptr_t)(flags ? self->GetObjectRaw() : self->GetObject());
384 void* indexed_obj = (void*)(address+(uintptr_t)(idx*sz));
385
386 return BindCppObjectNoCast(indexed_obj, ((CPPClass*)Py_TYPE(self))->fCppType, flags);
387}
388
389//- sequence methods --------------------------------------------------------
391 0, // sq_length
392 0, // sq_concat
393 0, // sq_repeat
394 (ssizeargfunc)op_item, // sq_item
395 0, // sq_slice
396 0, // sq_ass_item
397 0, // sq_ass_slice
398 0, // sq_contains
399 0, // sq_inplace_concat
400 0, // sq_inplace_repeat
401};
402
403std::function<PyObject *(PyObject *)> &CPPInstance::ReduceMethod() {
404 static std::function<PyObject *(PyObject *)> reducer;
405 return reducer;
406}
407
409{
411 if (!reducer) {
413 return nullptr;
414 }
415 return reducer(self);
416}
417
418
419//----------------------------------------------------------------------------
421 {(char*)"__destruct__", (PyCFunction)op_destruct, METH_NOARGS,
422 (char*)"call the C++ destructor"},
423 {(char*)"__dispatch__", (PyCFunction)op_dispatch, METH_VARARGS,
424 (char*)"dispatch to selected overload"},
425 {(char*)"__smartptr__", (PyCFunction)op_get_smartptr, METH_NOARGS,
426 (char*)"get associated smart pointer, if any"},
427 {(char*)"__reduce__", (PyCFunction)op_reduce, METH_NOARGS,
428 (char*)"reduce method for serialization"},
429 {(char*)"__reshape__", (PyCFunction)op_reshape, METH_O,
430 (char*)"cast pointer to 1D array type"},
431 {(char*)nullptr, nullptr, 0, nullptr}
432};
433
434
435//= CPyCppyy object proxy construction/destruction ===========================
437{
438// Create a new object proxy (holder only).
439 CPPInstance* pyobj = (CPPInstance*)subtype->tp_alloc(subtype, 0);
440 pyobj->fObject = nullptr;
442
443 return pyobj;
444}
445
446//----------------------------------------------------------------------------
448{
449// Remove (Python-side) memory held by the object proxy.
453}
454
455//----------------------------------------------------------------------------
457{
458// Garbage collector clear of held python member objects; this is a good time
459// to safely remove this object from the memory regulator.
460 if (pyobj->fFlags & CPPInstance::kIsRegulated)
462
463 return 0;
464}
465
466//----------------------------------------------------------------------------
468{
469 using namespace Utility;
470
471// special case for C++11 style nullptr
472 if (obj == gNullPtrObject) {
473 void* rawcpp = ((CPPInstance*)self)->GetObjectRaw();
474 switch (op) {
475 case Py_EQ:
476 if (rawcpp == nullptr) Py_RETURN_TRUE;
478 case Py_NE:
479 if (rawcpp != nullptr) Py_RETURN_TRUE;
481 default:
482 return nullptr; // not implemented
483 }
484 }
485
486 if (!klass->fOperators)
487 klass->fOperators = new PyOperators{};
488
489 bool flipit = false;
490 PyObject* binop = op == Py_EQ ? klass->fOperators->fEq : klass->fOperators->fNe;
491 if (!binop) {
492 const char* cppop = op == Py_EQ ? "==" : "!=";
493 PyCallable* pyfunc = FindBinaryOperator(self, obj, cppop);
495 else {
497 binop = Py_None;
498 }
499 // sets the operator to Py_None if not found, indicating that search was done
500 if (op == Py_EQ) klass->fOperators->fEq = binop;
501 else klass->fOperators->fNe = binop;
502 }
503
504 if (binop == Py_None) { // can try !== or !!= as alternatives
505 binop = op == Py_EQ ? klass->fOperators->fNe : klass->fOperators->fEq;
506 if (binop && binop != Py_None) flipit = true;
507 }
508
509 if (!binop || binop == Py_None) return nullptr;
510
511 PyObject* args = PyTuple_New(1);
512 Py_INCREF(obj); PyTuple_SET_ITEM(args, 0, obj);
513// since this overload is "ours", don't have to worry about rebinding
514 ((CPPOverload*)binop)->fSelf = (CPPInstance*)self;
515 PyObject* result = CPPOverload_Type.tp_call(binop, args, nullptr);
516 ((CPPOverload*)binop)->fSelf = nullptr;
517 Py_DECREF(args);
518
519 if (!result) {
520 PyErr_Clear();
521 return nullptr;
522 }
523
524// successful result, but may need to reverse the outcome
525 if (!flipit) return result;
526
529 if (istrue) {
531 }
533}
534
535static inline void* cast_actual(void* obj) {
536 void* address = ((CPPInstance*)obj)->GetObject();
538 return address;
539
540 Cppyy::TCppType_t klass = ((CPPClass*)Py_TYPE((PyObject*)obj))->fCppType;
542 if (clActual && clActual != klass) {
543 intptr_t offset = Cppyy::GetBaseOffset(
544 clActual, klass, address, -1 /* down-cast */, true /* report errors */);
545 if (offset != -1) address = (void*)((intptr_t)address + offset);
546 }
547
548 return address;
549}
550
551
552#define CPYCPPYY_ORDERED_OPERATOR_STUB(op, ometh, label) \
553 if (!ometh) { \
554 PyCallable* pyfunc = Utility::FindBinaryOperator((PyObject*)self, other, #op);\
555 if (pyfunc) \
556 ometh = (PyObject*)CPPOverload_New(#label, pyfunc); \
557 } \
558 meth = ometh;
559
561{
562// Rich set of comparison objects; currently supported:
563// == : Py_EQ
564// != : Py_NE
565//
566// < : Py_LT
567// <= : Py_LE
568// > : Py_GT
569// >= : Py_GE
570//
571
572// associative comparison operators
573 if (op == Py_EQ || op == Py_NE) {
574 // special case for None to compare True to a null-pointer
575 if ((PyObject*)other == Py_None && !self->fObject) {
576 const char *msg =
577 "\nComparison of C++ nullptr objects with `None` is deprecated and will raise a TypeError starting from ROOT 6.40."
578 "\n\nThis currently treats `None` as equivalent to a null C++ pointer, which may lead to confusing results."
579 "\nFor example, `x == None` may return True even though `x is None` is False."
580 "\n\nTo test whether a C++ object is null or not, check its truth value instead:"
581 "\n if not x: ..."
582 "\nor use `x is None` to explicitly check for Python None."
583 "\n";
584
585 // Equivalent to: warnings.warn(msg, FutureWarning, stacklevel=0)
586 if (PyErr_WarnEx(PyExc_FutureWarning, msg, 0) < 0) {
587 return NULL; // Propagate the error if warning turned into an exception
588 }
589 if (op == Py_EQ) { Py_RETURN_TRUE; }
591 }
592
593 // use C++-side operators if available
597 if (result) return result;
598
599 // default behavior: type + held pointer value defines identity; if both are
600 // CPPInstance objects, perform an additional autocast if need be
601 bool bIsEq = false;
602
603 if ((Py_TYPE(self) == Py_TYPE(other) && \
604 self->GetObject() == ((CPPInstance*)other)->GetObject())) {
605 // direct match
606 bIsEq = true;
607 } else if (CPPInstance_Check(other)) {
608 // try auto-cast match
609 void* addr1 = cast_actual(self);
610 void* addr2 = cast_actual(other);
611 bIsEq = addr1 && addr2 && (addr1 == addr2);
612 }
613
614 if ((op == Py_EQ && bIsEq) || (op == Py_NE && !bIsEq))
616
618 }
619
620// ordered comparison operators
621 else if (op == Py_LT || op == Py_LE || op == Py_GT || op == Py_GE) {
623 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};
624 PyObject* meth = nullptr;
625
626 switch (op) {
627 case Py_LT:
628 CPYCPPYY_ORDERED_OPERATOR_STUB(<, klass->fOperators->fLt, __lt__)
629 break;
630 case Py_LE:
631 CPYCPPYY_ORDERED_OPERATOR_STUB(<=, klass->fOperators->fLe, __ge__)
632 break;
633 case Py_GT:
634 CPYCPPYY_ORDERED_OPERATOR_STUB(>, klass->fOperators->fGt, __gt__)
635 break;
636 case Py_GE:
637 CPYCPPYY_ORDERED_OPERATOR_STUB(>=, klass->fOperators->fGe, __ge__)
638 break;
639 }
640
641 if (!meth) {
643 return nullptr;
644 }
645
647 }
648
650 return Py_NotImplemented;
651}
652
653//----------------------------------------------------------------------------
655{
656// Build a representation string of the object proxy that shows the address
657// of the C++ object that is held, as well as its type.
660 return PyBaseObject_Type.tp_repr((PyObject*)self);
662
663 Cppyy::TCppType_t klass = self->ObjectIsA();
664 std::string clName = klass ? Cppyy::GetFinalName(klass) : "<unknown>";
665 if (self->fFlags & CPPInstance::kIsPtrPtr)
666 clName.append("**");
667 else if (self->fFlags & CPPInstance::kIsReference)
668 clName.append("*");
669
670 PyObject* repr = nullptr;
671 if (self->IsSmart()) {
674 const_cast<char*>("<%s.%s object at %p held by %s at %p>"),
676 self->GetObject(), smartPtrName.c_str(), self->GetObjectRaw());
677 } else {
678 repr = CPyCppyy_PyText_FromFormat(const_cast<char*>("<%s.%s object at %p>"),
679 CPyCppyy_PyText_AsString(modname), clName.c_str(), self->GetObject());
680 }
681
683 return repr;
684}
685
686//----------------------------------------------------------------------------
688{
689// Cannot use PyLong_AsSize_t here, as it cuts of at PY_SSIZE_T_MAX, which is
690// only half of the max of std::size_t returned by the hash.
691 if (sizeof(unsigned long) >= sizeof(size_t))
692 return (Py_hash_t)PyLong_AsUnsignedLong(obj);
694}
695
697{
698// Try to locate an std::hash for this type and use that if it exists
700 if (klass->fOperators && klass->fOperators->fHash) {
701 Py_hash_t h = 0;
702 PyObject* hashval = PyObject_CallFunctionObjArgs(klass->fOperators->fHash, (PyObject*)self, nullptr);
703 if (hashval) {
706 }
707 return h;
708 }
709
711 if (stdhash) {
714 bool isValid = PyMapping_HasKeyString(dct, (char*)"__call__");
715 Py_DECREF(dct);
716 if (isValid) {
718 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};
719 klass->fOperators->fHash = hashobj;
721
722 Py_hash_t h = 0;
724 if (hashval) {
727 }
728 return h;
729 }
731 }
732
733// if not valid, simply reset the hash function so as to not kill performance
735 return PyBaseObject_Type.tp_hash((PyObject*)self);
736}
737
738//----------------------------------------------------------------------------
740{
741 static Cppyy::TCppScope_t sOStringStreamID = Cppyy::GetScope("std::ostringstream");
742 std::ostringstream s;
744 Py_INCREF(pys);
745#if PY_VERSION_HEX >= 0x03000000
746// for py3 and later, a ref-count of 2 is okay to consider the object temporary, but
747// in this case, we can't lose our existing ostrinstring (otherwise, we'd have to peel
748// it out of the return value, if moves are used
749 Py_INCREF(pys);
750#endif
751
752 PyObject* res;
755
756 Py_DECREF(pys);
757#if PY_VERSION_HEX >= 0x03000000
758 Py_DECREF(pys);
759#endif
760
761 if (res) {
762 Py_DECREF(res);
763 return CPyCppyy_PyText_FromString(s.str().c_str());
764 }
765
766 return nullptr;
767}
768
769
771 return ((CPPScope*)Py_TYPE((PyObject*)self))->fFlags & flag;
772}
773
775 ((CPPScope*)Py_TYPE((PyObject*)self))->fFlags |= flag;
776}
777
779{
780// There are three possible options here:
781// 1. Available operator<< to convert through an ostringstream
782// 2. Cling's pretty printing
783// 3. Generic printing as done in op_repr
784//
785// Additionally, there may be a mapped __str__ from the C++ type defining `operator char*`
786// or `operator const char*`. Results are memoized for performance reasons.
787
788// 0. Protect against trying to print a typed nullptr object through an insertion operator
789 if (!self->GetObject())
790 return op_repr(self);
791
792// 1. Available operator<< to convert through an ostringstream
796 continue;
797
798 else if (pyname == (PyObject*)0x01) {
799 // normal lookup failed; attempt lazy install of global operator<<(ostream&, type&)
800 std::string rcname = Utility::ClassName((PyObject*)self);
802 PyCallable* pyfunc = Utility::FindBinaryOperator("std::ostream", rcname, "<<", rnsID);
803 if (!pyfunc)
804 continue;
805
807
810
811 } else if (pyname == (PyObject*)0x02) {
812 // TODO: the only reason this still exists, is b/c friend functions are otherwise not found
813 // TODO: ToString() still leaks ...
814 const std::string& pretty = Cppyy::ToString(self->ObjectIsA(), self->GetObject());
815 if (!pretty.empty())
816 return CPyCppyy_PyText_FromString(pretty.c_str());
817 continue;
818 }
819
822
823 if (lshift) {
826 if (result)
827 return result;
828 }
829
830 PyErr_Clear();
831 }
832
833 // failed ostream printing; don't try again
835 }
836
837// 2. Cling's pretty printing (not done through backend for performance reasons)
839 static PyObject* printValue = nullptr;
840 if (!printValue) {
841 PyObject* gbl = PyDict_GetItemString(PySys_GetObject((char*)"modules"), "cppyy.gbl");
842 PyObject* cl = PyObject_GetAttrString(gbl, (char*)"cling");
843 printValue = PyObject_GetAttrString(cl, (char*)"printValue");
844 Py_DECREF(cl);
845 // gbl is borrowed
846 if (printValue) {
847 Py_DECREF(printValue); // make borrowed
848 if (!PyCallable_Check(printValue))
849 printValue = nullptr; // unusable ...
850 }
851 if (!printValue) // unlikely
853 }
854
855 if (printValue) {
856 // as printValue only works well for templates taking pointer arguments, we'll
857 // have to force the issue by working with a by-ptr object
858 Cppyy::TCppObject_t cppobj = self->GetObjectRaw();
860 if (!(self->fFlags & CPPInstance::kIsReference)) {
863 } else {
865 }
866
867 // explicit template lookup
869 PyObject* OL = PyObject_GetItem(printValue, clName);
871
872 PyObject* pretty = OL ? PyObject_CallFunctionObjArgs(OL, byref, nullptr) : nullptr;
873 Py_XDECREF(OL);
875
876 PyObject* result = nullptr;
877 if (pretty) {
878 const std::string& pv = *(std::string*)((CPPInstance*)pretty)->GetObject();
879 if (!pv.empty() && pv.find("@0x") == std::string::npos)
882 if (result) return result;
883 }
884
885 PyErr_Clear();
886 }
887
888 // if not available/specialized, don't try again
890 }
891
892// 3. Generic printing as done in op_repr
893 return op_repr(self);
894}
895
896//-----------------------------------------------------------------------------
898{
899 return PyBool_FromLong((long)(pyobj->fFlags & CPPInstance::kIsOwner));
900}
901
902//-----------------------------------------------------------------------------
904{
905// Set the ownership (True is python-owns) for the given object.
907 if (shouldown == -1 && PyErr_Occurred()) {
908 PyErr_SetString(PyExc_ValueError, "__python_owns__ should be either True or False");
909 return -1;
910 }
911
912 (bool)shouldown ? pyobj->PythonOwns() : pyobj->CppOwns();
913
914 return 0;
915}
916
917
918//-----------------------------------------------------------------------------
920 {(char*)"__python_owns__", (getter)op_getownership, (setter)op_setownership,
921 (char*)"If true, python manages the life time of this object", nullptr},
922 {(char*)nullptr, nullptr, nullptr, nullptr, nullptr}
923};
924
925
926//= CPyCppyy type number stubs to allow dynamic overrides =====================
927#define CPYCPPYY_STUB_BODY(name, op) \
928 bool previously_resolved_overload = (bool)meth; \
929 if (!meth) { \
930 PyErr_Clear(); \
931 PyCallable* pyfunc = Utility::FindBinaryOperator(left, right, #op); \
932 if (pyfunc) meth = (PyObject*)CPPOverload_New(#name, pyfunc); \
933 else { \
934 PyErr_SetString(PyExc_NotImplementedError, ""); \
935 return nullptr; \
936 } \
937 } \
938 PyObject* res = PyObject_CallFunctionObjArgs(meth, cppobj, other, nullptr);\
939 if (!res && previously_resolved_overload) { \
940 /* try again, in case (left, right) are different types than before */ \
941 PyErr_Clear(); \
942 PyCallable* pyfunc = Utility::FindBinaryOperator(left, right, #op); \
943 if (pyfunc) ((CPPOverload*&)meth)->AdoptMethod(pyfunc); \
944 else { \
945 PyErr_SetString(PyExc_NotImplementedError, ""); \
946 return nullptr; \
947 } \
948 /* use same overload with newly added function */ \
949 res = PyObject_CallFunctionObjArgs(meth, cppobj, other, nullptr); \
950 } \
951 return res;
952
953
954#define CPYCPPYY_OPERATOR_STUB(name, op, ometh) \
955static PyObject* op_##name##_stub(PyObject* left, PyObject* right) \
956{ \
957/* placeholder to lazily install and forward to 'ometh' if available */ \
958 CPPClass* klass = (CPPClass*)Py_TYPE(left); \
959 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{}; \
960 PyObject*& meth = ometh; \
961 PyObject *cppobj = left, *other = right; \
962 CPYCPPYY_STUB_BODY(name, op) \
963}
964
965#define CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(name, op, lmeth, rmeth) \
966static PyObject* op_##name##_stub(PyObject* left, PyObject* right) \
967{ \
968/* placeholder to lazily install and forward do '(l/r)meth' if available */ \
969 CPPClass* klass; PyObject** pmeth; \
970 PyObject *cppobj, *other; \
971 if (CPPInstance_Check(left)) { \
972 klass = (CPPClass*)Py_TYPE(left); \
973 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};\
974 pmeth = &lmeth; cppobj = left; other = right; \
975 } else if (CPPInstance_Check(right)) { \
976 klass = (CPPClass*)Py_TYPE(right); \
977 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};\
978 pmeth = &rmeth; cppobj = right; other = left; \
979 } else { \
980 PyErr_SetString(PyExc_NotImplementedError, ""); \
981 return nullptr; \
982 } \
983 PyObject*& meth = *pmeth; \
984 CPYCPPYY_STUB_BODY(name, op) \
985}
986
987#define CPYCPPYY_UNARY_OPERATOR(name, op, label) \
988static PyObject* op_##name##_stub(PyObject* pyobj) \
989{ \
990/* placeholder to lazily install unary operators */ \
991 PyCallable* pyfunc = Utility::FindUnaryOperator((PyObject*)Py_TYPE(pyobj), #op);\
992 if (pyfunc && Utility::AddToClass((PyObject*)Py_TYPE(pyobj), #label, pyfunc))\
993 return PyObject_CallMethod(pyobj, (char*)#label, nullptr); \
994 PyErr_SetString(PyExc_NotImplementedError, ""); \
995 return nullptr; \
996}
997
998CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(add, +, klass->fOperators->fLAdd, klass->fOperators->fRAdd)
999CPYCPPYY_OPERATOR_STUB( sub, -, klass->fOperators->fSub)
1000CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(mul, *, klass->fOperators->fLMul, klass->fOperators->fRMul)
1001CPYCPPYY_OPERATOR_STUB( div, /, klass->fOperators->fDiv)
1005
1006//-----------------------------------------------------------------------------
1008 (binaryfunc)op_add_stub, // nb_add
1009 (binaryfunc)op_sub_stub, // nb_subtract
1010 (binaryfunc)op_mul_stub, // nb_multiply
1011#if PY_VERSION_HEX < 0x03000000
1012 (binaryfunc)op_div_stub, // nb_divide
1013#endif
1014 0, // nb_remainder
1015 0, // nb_divmod
1016 0, // nb_power
1017 (unaryfunc)op_neg_stub, // nb_negative
1018 (unaryfunc)op_pos_stub, // nb_positive
1019 0, // nb_absolute
1020 (inquiry)op_nonzero, // nb_bool (nb_nonzero in p2)
1021 (unaryfunc)op_invert_stub, // nb_invert
1022 0, // nb_lshift
1023 0, // nb_rshift
1024 0, // nb_and
1025 0, // nb_xor
1026 0, // nb_or
1027#if PY_VERSION_HEX < 0x03000000
1028 0, // nb_coerce
1029#endif
1030 0, // nb_int
1031 0, // nb_long (nb_reserved in p3)
1032 0, // nb_float
1033#if PY_VERSION_HEX < 0x03000000
1034 0, // nb_oct
1035 0, // nb_hex
1036#endif
1037 0, // nb_inplace_add
1038 0, // nb_inplace_subtract
1039 0, // nb_inplace_multiply
1040#if PY_VERSION_HEX < 0x03000000
1041 0, // nb_inplace_divide
1042#endif
1043 0, // nb_inplace_remainder
1044 0, // nb_inplace_power
1045 0, // nb_inplace_lshift
1046 0, // nb_inplace_rshift
1047 0, // nb_inplace_and
1048 0, // nb_inplace_xor
1049 0 // nb_inplace_or
1050#if PY_VERSION_HEX >= 0x02020000
1051 , 0 // nb_floor_divide
1052#if PY_VERSION_HEX < 0x03000000
1053 , 0 // nb_true_divide
1054#else
1055 , (binaryfunc)op_div_stub // nb_true_divide
1056#endif
1057 , 0 // nb_inplace_floor_divide
1058 , 0 // nb_inplace_true_divide
1059#endif
1060#if PY_VERSION_HEX >= 0x02050000
1061 , 0 // nb_index
1062#endif
1063#if PY_VERSION_HEX >= 0x03050000
1064 , 0 // nb_matrix_multiply
1065 , 0 // nb_inplace_matrix_multiply
1066#endif
1067};
1068
1069
1070//= CPyCppyy object proxy type ===============================================
1073 (char*)"cppyy.CPPInstance", // tp_name
1074 sizeof(CPPInstance), // tp_basicsize
1075 0, // tp_itemsize
1076 (destructor)op_dealloc, // tp_dealloc
1077 0, // tp_vectorcall_offset / tp_print
1078 0, // tp_getattr
1079 0, // tp_setattr
1080 0, // tp_as_async / tp_compare
1081 (reprfunc)op_repr, // tp_repr
1082 &op_as_number, // tp_as_number
1083 &op_as_sequence, // tp_as_sequence
1084 0, // tp_as_mapping
1085 (hashfunc)op_hash, // tp_hash
1086 0, // tp_call
1087 (reprfunc)op_str, // tp_str
1088 0, // tp_getattro
1089 0, // tp_setattro
1090 0, // tp_as_buffer
1094 Py_TPFLAGS_HAVE_GC, // tp_flags
1095 (char*)"cppyy object proxy (internal)", // tp_doc
1096 (traverseproc)op_traverse, // tp_traverse
1097 (inquiry)op_clear, // tp_clear
1098 (richcmpfunc)op_richcompare, // tp_richcompare
1099 0, // tp_weaklistoffset
1100 0, // tp_iter
1101 0, // tp_iternext
1102 op_methods, // tp_methods
1103 0, // tp_members
1104 op_getset, // tp_getset
1105 0, // tp_base
1106 0, // tp_dict
1107 0, // tp_descr_get
1108 0, // tp_descr_set
1109 0, // tp_dictoffset
1110 0, // tp_init
1111 0, // tp_alloc
1112 (newfunc)op_new, // tp_new
1113 0, // tp_free
1114 0, // tp_is_gc
1115 0, // tp_bases
1116 0, // tp_mro
1117 0, // tp_cache
1118 0, // tp_subclasses
1119 0 // tp_weaklist
1120#if PY_VERSION_HEX >= 0x02030000
1121 , 0 // tp_del
1122#endif
1123#if PY_VERSION_HEX >= 0x02060000
1124 , 0 // tp_version_tag
1125#endif
1126#if PY_VERSION_HEX >= 0x03040000
1127 , 0 // tp_finalize
1128#endif
1129#if PY_VERSION_HEX >= 0x03080000
1130 , 0 // tp_vectorcall
1131#endif
1132#if PY_VERSION_HEX >= 0x030c0000
1133 , 0 // tp_watched
1134#endif
1135#if PY_VERSION_HEX >= 0x030d0000
1136 , 0 // tp_versions_used
1137#endif
1138};
1139
1140} // 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
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
_object PyObject
std::ios_base::fmtflags fFlags
#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
static std::function< PyObject *(PyObject *)> ReduceMethod)()
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:49
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:298
bool AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Definition Utility.cxx:186
std::string ClassName(PyObject *pyobj)
Definition Utility.cxx:1068
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)
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:25
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:647
PyObject * op_reduce(PyObject *self, PyObject *)
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)