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 no longer supported."
578 "\n\nPreviously, `None` was treated as equivalent to a null C++ pointer, "
579 "but this led to confusing behavior where `x == None` could be True even though `x is None` was 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
586 return NULL; // stop execution, raise TypeError
587 }
588
589 // use C++-side operators if available
593 if (result) return result;
594
595 // default behavior: type + held pointer value defines identity; if both are
596 // CPPInstance objects, perform an additional autocast if need be
597 bool bIsEq = false;
598
599 if ((Py_TYPE(self) == Py_TYPE(other) && \
600 self->GetObject() == ((CPPInstance*)other)->GetObject())) {
601 // direct match
602 bIsEq = true;
603 } else if (CPPInstance_Check(other)) {
604 // try auto-cast match
605 void* addr1 = cast_actual(self);
606 void* addr2 = cast_actual(other);
607 bIsEq = addr1 && addr2 && (addr1 == addr2);
608 }
609
610 if ((op == Py_EQ && bIsEq) || (op == Py_NE && !bIsEq))
612
614 }
615
616// ordered comparison operators
617 else if (op == Py_LT || op == Py_LE || op == Py_GT || op == Py_GE) {
619 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};
620 PyObject* meth = nullptr;
621
622 switch (op) {
623 case Py_LT:
624 CPYCPPYY_ORDERED_OPERATOR_STUB(<, klass->fOperators->fLt, __lt__)
625 break;
626 case Py_LE:
627 CPYCPPYY_ORDERED_OPERATOR_STUB(<=, klass->fOperators->fLe, __ge__)
628 break;
629 case Py_GT:
630 CPYCPPYY_ORDERED_OPERATOR_STUB(>, klass->fOperators->fGt, __gt__)
631 break;
632 case Py_GE:
633 CPYCPPYY_ORDERED_OPERATOR_STUB(>=, klass->fOperators->fGe, __ge__)
634 break;
635 }
636
637 if (!meth) {
639 return nullptr;
640 }
641
643 }
644
646 return Py_NotImplemented;
647}
648
649//----------------------------------------------------------------------------
651{
652// Build a representation string of the object proxy that shows the address
653// of the C++ object that is held, as well as its type.
656 return PyBaseObject_Type.tp_repr((PyObject*)self);
658
659 Cppyy::TCppType_t klass = self->ObjectIsA();
660 std::string clName = klass ? Cppyy::GetFinalName(klass) : "<unknown>";
661 if (self->fFlags & CPPInstance::kIsPtrPtr)
662 clName.append("**");
663 else if (self->fFlags & CPPInstance::kIsReference)
664 clName.append("*");
665
666 PyObject* repr = nullptr;
667 if (self->IsSmart()) {
670 const_cast<char*>("<%s.%s object at %p held by %s at %p>"),
672 self->GetObject(), smartPtrName.c_str(), self->GetObjectRaw());
673 } else {
674 repr = CPyCppyy_PyText_FromFormat(const_cast<char*>("<%s.%s object at %p>"),
675 CPyCppyy_PyText_AsString(modname), clName.c_str(), self->GetObject());
676 }
677
679 return repr;
680}
681
682//----------------------------------------------------------------------------
684{
685// Cannot use PyLong_AsSize_t here, as it cuts of at PY_SSIZE_T_MAX, which is
686// only half of the max of std::size_t returned by the hash.
687 if (sizeof(unsigned long) >= sizeof(size_t))
688 return (Py_hash_t)PyLong_AsUnsignedLong(obj);
690}
691
693{
694// Try to locate an std::hash for this type and use that if it exists
696 if (klass->fOperators && klass->fOperators->fHash) {
697 Py_hash_t h = 0;
698 PyObject* hashval = PyObject_CallFunctionObjArgs(klass->fOperators->fHash, (PyObject*)self, nullptr);
699 if (hashval) {
702 }
703 return h;
704 }
705
707 if (stdhash) {
710 bool isValid = PyMapping_HasKeyString(dct, (char*)"__call__");
711 Py_DECREF(dct);
712 if (isValid) {
714 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};
715 klass->fOperators->fHash = hashobj;
717
718 Py_hash_t h = 0;
720 if (hashval) {
723 }
724 return h;
725 }
727 }
728
729// if not valid, simply reset the hash function so as to not kill performance
731 return PyBaseObject_Type.tp_hash((PyObject*)self);
732}
733
734//----------------------------------------------------------------------------
736{
737 static Cppyy::TCppScope_t sOStringStreamID = Cppyy::GetScope("std::ostringstream");
738 std::ostringstream s;
740 Py_INCREF(pys);
741#if PY_VERSION_HEX >= 0x03000000
742// for py3 and later, a ref-count of 2 is okay to consider the object temporary, but
743// in this case, we can't lose our existing ostrinstring (otherwise, we'd have to peel
744// it out of the return value, if moves are used
745 Py_INCREF(pys);
746#endif
747
748 PyObject* res;
751
752 Py_DECREF(pys);
753#if PY_VERSION_HEX >= 0x03000000
754 Py_DECREF(pys);
755#endif
756
757 if (res) {
758 Py_DECREF(res);
759 return CPyCppyy_PyText_FromString(s.str().c_str());
760 }
761
762 return nullptr;
763}
764
765
767 return ((CPPScope*)Py_TYPE((PyObject*)self))->fFlags & flag;
768}
769
771 ((CPPScope*)Py_TYPE((PyObject*)self))->fFlags |= flag;
772}
773
775{
776// There are three possible options here:
777// 1. Available operator<< to convert through an ostringstream
778// 2. Cling's pretty printing
779// 3. Generic printing as done in op_repr
780//
781// Additionally, there may be a mapped __str__ from the C++ type defining `operator char*`
782// or `operator const char*`. Results are memoized for performance reasons.
783
784// 0. Protect against trying to print a typed nullptr object through an insertion operator
785 if (!self->GetObject())
786 return op_repr(self);
787
788// 1. Available operator<< to convert through an ostringstream
792 continue;
793
794 else if (pyname == (PyObject*)0x01) {
795 // normal lookup failed; attempt lazy install of global operator<<(ostream&, type&)
796 std::string rcname = Utility::ClassName((PyObject*)self);
798 PyCallable* pyfunc = Utility::FindBinaryOperator("std::ostream", rcname, "<<", rnsID);
799 if (!pyfunc)
800 continue;
801
803
806
807 } else if (pyname == (PyObject*)0x02) {
808 // TODO: the only reason this still exists, is b/c friend functions are otherwise not found
809 // TODO: ToString() still leaks ...
810 const std::string& pretty = Cppyy::ToString(self->ObjectIsA(), self->GetObject());
811 if (!pretty.empty())
812 return CPyCppyy_PyText_FromString(pretty.c_str());
813 continue;
814 }
815
818
819 if (lshift) {
822 if (result)
823 return result;
824 }
825
826 PyErr_Clear();
827 }
828
829 // failed ostream printing; don't try again
831 }
832
833// 2. Cling's pretty printing (not done through backend for performance reasons)
835 static PyObject* printValue = nullptr;
836 if (!printValue) {
837 PyObject* gbl = PyDict_GetItemString(PySys_GetObject((char*)"modules"), "cppyy.gbl");
838 PyObject* cl = PyObject_GetAttrString(gbl, (char*)"cling");
839 printValue = PyObject_GetAttrString(cl, (char*)"printValue");
840 Py_DECREF(cl);
841 // gbl is borrowed
842 if (printValue) {
843 Py_DECREF(printValue); // make borrowed
844 if (!PyCallable_Check(printValue))
845 printValue = nullptr; // unusable ...
846 }
847 if (!printValue) // unlikely
849 }
850
851 if (printValue) {
852 // as printValue only works well for templates taking pointer arguments, we'll
853 // have to force the issue by working with a by-ptr object
854 Cppyy::TCppObject_t cppobj = self->GetObjectRaw();
856 if (!(self->fFlags & CPPInstance::kIsReference)) {
859 } else {
861 }
862
863 // explicit template lookup
865 PyObject* OL = PyObject_GetItem(printValue, clName);
867
868 PyObject* pretty = OL ? PyObject_CallFunctionObjArgs(OL, byref, nullptr) : nullptr;
869 Py_XDECREF(OL);
871
872 PyObject* result = nullptr;
873 if (pretty) {
874 const std::string& pv = *(std::string*)((CPPInstance*)pretty)->GetObject();
875 if (!pv.empty() && pv.find("@0x") == std::string::npos)
878 if (result) return result;
879 }
880
881 PyErr_Clear();
882 }
883
884 // if not available/specialized, don't try again
886 }
887
888// 3. Generic printing as done in op_repr
889 return op_repr(self);
890}
891
892//-----------------------------------------------------------------------------
894{
895 return PyBool_FromLong((long)(pyobj->fFlags & CPPInstance::kIsOwner));
896}
897
898//-----------------------------------------------------------------------------
900{
901// Set the ownership (True is python-owns) for the given object.
903 if (shouldown == -1 && PyErr_Occurred()) {
904 PyErr_SetString(PyExc_ValueError, "__python_owns__ should be either True or False");
905 return -1;
906 }
907
908 (bool)shouldown ? pyobj->PythonOwns() : pyobj->CppOwns();
909
910 return 0;
911}
912
913
914//-----------------------------------------------------------------------------
916 {(char*)"__python_owns__", (getter)op_getownership, (setter)op_setownership,
917 (char*)"If true, python manages the life time of this object", nullptr},
918 {(char*)nullptr, nullptr, nullptr, nullptr, nullptr}
919};
920
921
922//= CPyCppyy type number stubs to allow dynamic overrides =====================
923#define CPYCPPYY_STUB_BODY(name, op) \
924 bool previously_resolved_overload = (bool)meth; \
925 if (!meth) { \
926 PyErr_Clear(); \
927 PyCallable* pyfunc = Utility::FindBinaryOperator(left, right, #op); \
928 if (pyfunc) meth = (PyObject*)CPPOverload_New(#name, pyfunc); \
929 else { \
930 PyErr_SetString(PyExc_NotImplementedError, ""); \
931 return nullptr; \
932 } \
933 } \
934 PyObject* res = PyObject_CallFunctionObjArgs(meth, cppobj, other, nullptr);\
935 if (!res && previously_resolved_overload) { \
936 /* try again, in case (left, right) are different types than before */ \
937 PyErr_Clear(); \
938 PyCallable* pyfunc = Utility::FindBinaryOperator(left, right, #op); \
939 if (pyfunc) ((CPPOverload*&)meth)->AdoptMethod(pyfunc); \
940 else { \
941 PyErr_SetString(PyExc_NotImplementedError, ""); \
942 return nullptr; \
943 } \
944 /* use same overload with newly added function */ \
945 res = PyObject_CallFunctionObjArgs(meth, cppobj, other, nullptr); \
946 } \
947 return res;
948
949
950#define CPYCPPYY_OPERATOR_STUB(name, op, ometh) \
951static PyObject* op_##name##_stub(PyObject* left, PyObject* right) \
952{ \
953/* placeholder to lazily install and forward to 'ometh' if available */ \
954 CPPClass* klass = (CPPClass*)Py_TYPE(left); \
955 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{}; \
956 PyObject*& meth = ometh; \
957 PyObject *cppobj = left, *other = right; \
958 CPYCPPYY_STUB_BODY(name, op) \
959}
960
961#define CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(name, op, lmeth, rmeth) \
962static PyObject* op_##name##_stub(PyObject* left, PyObject* right) \
963{ \
964/* placeholder to lazily install and forward do '(l/r)meth' if available */ \
965 CPPClass* klass; PyObject** pmeth; \
966 PyObject *cppobj, *other; \
967 if (CPPInstance_Check(left)) { \
968 klass = (CPPClass*)Py_TYPE(left); \
969 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};\
970 pmeth = &lmeth; cppobj = left; other = right; \
971 } else if (CPPInstance_Check(right)) { \
972 klass = (CPPClass*)Py_TYPE(right); \
973 if (!klass->fOperators) klass->fOperators = new Utility::PyOperators{};\
974 pmeth = &rmeth; cppobj = right; other = left; \
975 } else { \
976 PyErr_SetString(PyExc_NotImplementedError, ""); \
977 return nullptr; \
978 } \
979 PyObject*& meth = *pmeth; \
980 CPYCPPYY_STUB_BODY(name, op) \
981}
982
983#define CPYCPPYY_UNARY_OPERATOR(name, op, label) \
984static PyObject* op_##name##_stub(PyObject* pyobj) \
985{ \
986/* placeholder to lazily install unary operators */ \
987 PyCallable* pyfunc = Utility::FindUnaryOperator((PyObject*)Py_TYPE(pyobj), #op);\
988 if (pyfunc && Utility::AddToClass((PyObject*)Py_TYPE(pyobj), #label, pyfunc))\
989 return PyObject_CallMethod(pyobj, (char*)#label, nullptr); \
990 PyErr_SetString(PyExc_NotImplementedError, ""); \
991 return nullptr; \
992}
993
994CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(add, +, klass->fOperators->fLAdd, klass->fOperators->fRAdd)
995CPYCPPYY_OPERATOR_STUB( sub, -, klass->fOperators->fSub)
996CPYCPPYY_ASSOCIATIVE_OPERATOR_STUB(mul, *, klass->fOperators->fLMul, klass->fOperators->fRMul)
997CPYCPPYY_OPERATOR_STUB( div, /, klass->fOperators->fDiv)
1001
1002//-----------------------------------------------------------------------------
1004 (binaryfunc)op_add_stub, // nb_add
1005 (binaryfunc)op_sub_stub, // nb_subtract
1006 (binaryfunc)op_mul_stub, // nb_multiply
1007#if PY_VERSION_HEX < 0x03000000
1008 (binaryfunc)op_div_stub, // nb_divide
1009#endif
1010 0, // nb_remainder
1011 0, // nb_divmod
1012 0, // nb_power
1013 (unaryfunc)op_neg_stub, // nb_negative
1014 (unaryfunc)op_pos_stub, // nb_positive
1015 0, // nb_absolute
1016 (inquiry)op_nonzero, // nb_bool (nb_nonzero in p2)
1017 (unaryfunc)op_invert_stub, // nb_invert
1018 0, // nb_lshift
1019 0, // nb_rshift
1020 0, // nb_and
1021 0, // nb_xor
1022 0, // nb_or
1023#if PY_VERSION_HEX < 0x03000000
1024 0, // nb_coerce
1025#endif
1026 0, // nb_int
1027 0, // nb_long (nb_reserved in p3)
1028 0, // nb_float
1029#if PY_VERSION_HEX < 0x03000000
1030 0, // nb_oct
1031 0, // nb_hex
1032#endif
1033 0, // nb_inplace_add
1034 0, // nb_inplace_subtract
1035 0, // nb_inplace_multiply
1036#if PY_VERSION_HEX < 0x03000000
1037 0, // nb_inplace_divide
1038#endif
1039 0, // nb_inplace_remainder
1040 0, // nb_inplace_power
1041 0, // nb_inplace_lshift
1042 0, // nb_inplace_rshift
1043 0, // nb_inplace_and
1044 0, // nb_inplace_xor
1045 0 // nb_inplace_or
1046#if PY_VERSION_HEX >= 0x02020000
1047 , 0 // nb_floor_divide
1048#if PY_VERSION_HEX < 0x03000000
1049 , 0 // nb_true_divide
1050#else
1051 , (binaryfunc)op_div_stub // nb_true_divide
1052#endif
1053 , 0 // nb_inplace_floor_divide
1054 , 0 // nb_inplace_true_divide
1055#endif
1056#if PY_VERSION_HEX >= 0x02050000
1057 , 0 // nb_index
1058#endif
1059#if PY_VERSION_HEX >= 0x03050000
1060 , 0 // nb_matrix_multiply
1061 , 0 // nb_inplace_matrix_multiply
1062#endif
1063};
1064
1065
1066//= CPyCppyy object proxy type ===============================================
1069 (char*)"cppyy.CPPInstance", // tp_name
1070 sizeof(CPPInstance), // tp_basicsize
1071 0, // tp_itemsize
1072 (destructor)op_dealloc, // tp_dealloc
1073 0, // tp_vectorcall_offset / tp_print
1074 0, // tp_getattr
1075 0, // tp_setattr
1076 0, // tp_as_async / tp_compare
1077 (reprfunc)op_repr, // tp_repr
1078 &op_as_number, // tp_as_number
1079 &op_as_sequence, // tp_as_sequence
1080 0, // tp_as_mapping
1081 (hashfunc)op_hash, // tp_hash
1082 0, // tp_call
1083 (reprfunc)op_str, // tp_str
1084 0, // tp_getattro
1085 0, // tp_setattro
1086 0, // tp_as_buffer
1090 Py_TPFLAGS_HAVE_GC, // tp_flags
1091 (char*)"cppyy object proxy (internal)", // tp_doc
1092 (traverseproc)op_traverse, // tp_traverse
1093 (inquiry)op_clear, // tp_clear
1094 (richcmpfunc)op_richcompare, // tp_richcompare
1095 0, // tp_weaklistoffset
1096 0, // tp_iter
1097 0, // tp_iternext
1098 op_methods, // tp_methods
1099 0, // tp_members
1100 op_getset, // tp_getset
1101 0, // tp_base
1102 0, // tp_dict
1103 0, // tp_descr_get
1104 0, // tp_descr_set
1105 0, // tp_dictoffset
1106 0, // tp_init
1107 0, // tp_alloc
1108 (newfunc)op_new, // tp_new
1109 0, // tp_free
1110 0, // tp_is_gc
1111 0, // tp_bases
1112 0, // tp_mro
1113 0, // tp_cache
1114 0, // tp_subclasses
1115 0 // tp_weaklist
1116#if PY_VERSION_HEX >= 0x02030000
1117 , 0 // tp_del
1118#endif
1119#if PY_VERSION_HEX >= 0x02060000
1120 , 0 // tp_version_tag
1121#endif
1122#if PY_VERSION_HEX >= 0x03040000
1123 , 0 // tp_finalize
1124#endif
1125#if PY_VERSION_HEX >= 0x03080000
1126 , 0 // tp_vectorcall
1127#endif
1128#if PY_VERSION_HEX >= 0x030c0000
1129 , 0 // tp_watched
1130#endif
1131#if PY_VERSION_HEX >= 0x030d0000
1132 , 0 // tp_versions_used
1133#endif
1134};
1135
1136} // 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)