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