Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Loading...
Searching...
No Matches
CPyCppyyModule.cxx
Go to the documentation of this file.
1// Bindings
2#include "CPyCppyy.h"
3#include "CallContext.h"
4#include "Converters.h"
5#include "CPPDataMember.h"
6#include "CPPExcInstance.h"
7#include "CPPInstance.h"
8#include "CPPOverload.h"
9#include "CPPScope.h"
10#include "CustomPyTypes.h"
11#include "LowLevelViews.h"
12#include "MemoryRegulator.h"
13#include "ProxyWrappers.h"
14#include "PyStrings.h"
15#include "TemplateProxy.h"
16#include "TupleOfInstances.h"
17#include "Utility.h"
18
19#define CPYCPPYY_INTERNAL 1
21namespace CPyCppyy {
24 void* addr, const std::string& classname, bool python_owns = false);
25} // namespace CPyCppyy
26#undef CPYCPPYY_INTERNAL
27
28// Standard
29#include <algorithm>
30#include <map>
31#include <set>
32#include <string>
33#include <iostream>
34#include <sstream>
35#include <utility>
36#include <vector>
37
38
39// Note: as of py3.11, dictionary objects no longer carry a function pointer for
40// the lookup, so it can no longer be shimmed and "from cppyy.interactive import *"
41// thus no longer works.
42#if PY_VERSION_HEX < 0x030b0000
43
44//- from Python's dictobject.c -------------------------------------------------
45#if PY_VERSION_HEX >= 0x03030000
46 typedef struct PyDictKeyEntry {
47 /* Cached hash code of me_key. */
50 PyObject *me_value; /* This field is only meaningful for combined tables */
52
53 typedef struct _dictkeysobject {
58#if PY_VERSION_HEX >= 0x03060000
60 union {
61 int8_t as_1[8];
62 int16_t as_2[4];
63 int32_t as_4[2];
64#if SIZEOF_VOID_P > 4
65 int64_t as_8[1];
66#endif
67 } dk_indices;
68#else
70#endif
72
73#define CPYCPPYY_GET_DICT_LOOKUP(mp) \
74 ((dict_lookup_func&)mp->ma_keys->dk_lookup)
75
76#else
77
78#define CPYCPPYY_GET_DICT_LOOKUP(mp) \
79 ((dict_lookup_func&)mp->ma_lookup)
80
81#endif
82
83#endif // PY_VERSION_HEX < 0x030b0000
84
85//- data -----------------------------------------------------------------------
87{
88 return CPyCppyy_PyText_FromString("nullptr");
89}
90
92{
93 Py_FatalError("deallocating nullptr");
94}
95
97{
98 return 0;
99}
100
102 0, 0, 0,
103#if PY_VERSION_HEX < 0x03000000
104 0,
105#endif
106 0, 0, 0, 0, 0, 0,
107 (inquiry)nullptr_nonzero, // tp_nonzero (nb_bool in p3)
108 0, 0, 0, 0, 0, 0,
109#if PY_VERSION_HEX < 0x03000000
110 0, // nb_coerce
111#endif
112 0, 0, 0,
113#if PY_VERSION_HEX < 0x03000000
114 0, 0,
115#endif
116 0, 0, 0,
117#if PY_VERSION_HEX < 0x03000000
118 0, // nb_inplace_divide
119#endif
120 0, 0, 0, 0, 0, 0, 0
121#if PY_VERSION_HEX >= 0x02020000
122 , 0 // nb_floor_divide
123#if PY_VERSION_HEX < 0x03000000
124 , 0 // nb_true_divide
125#else
126 , 0 // nb_true_divide
127#endif
128 , 0, 0
129#endif
130#if PY_VERSION_HEX >= 0x02050000
131 , 0 // nb_index
132#endif
133#if PY_VERSION_HEX >= 0x03050000
134 , 0 // nb_matrix_multiply
135 , 0 // nb_inplace_matrix_multiply
136#endif
137};
138
141 "nullptr_t", // tp_name
142 sizeof(PyObject), // tp_basicsize
143 0, // tp_itemsize
144 nullptr_dealloc, // tp_dealloc (never called)
145 0, 0, 0, 0,
146 nullptr_repr, // tp_repr
147 &nullptr_as_number, // tp_as_number
148 0, 0,
149 (hashfunc)_Py_HashPointer, // tp_hash
150 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT, 0, 0, 0, 0, 0, 0, 0,
151 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
152#if PY_VERSION_HEX >= 0x02030000
153 , 0 // tp_del
154#endif
155#if PY_VERSION_HEX >= 0x02060000
156 , 0 // tp_version_tag
157#endif
158#if PY_VERSION_HEX >= 0x03040000
159 , 0 // tp_finalize
160#endif
161#if PY_VERSION_HEX >= 0x03080000
162 , 0 // tp_vectorcall
163#endif
164#if PY_VERSION_HEX >= 0x030c0000
165 , 0 // tp_watched
166#endif
167#if PY_VERSION_HEX >= 0x030d0000
168 , 0 // tp_versions_used
169#endif
170};
171
172
174{
175 return CPyCppyy_PyText_FromString("type default");
176}
177
179{
180 Py_FatalError("deallocating default");
181}
182
185 "default_t", // tp_name
186 sizeof(PyObject), // tp_basicsize
187 0, // tp_itemsize
188 default_dealloc, // tp_dealloc (never called)
189 0, 0, 0, 0,
190 default_repr, // tp_repr
191 0, 0, 0,
192 (hashfunc)_Py_HashPointer, // tp_hash
193 0, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT, 0, 0, 0, 0, 0, 0, 0,
194 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
195#if PY_VERSION_HEX >= 0x02030000
196 , 0 // tp_del
197#endif
198#if PY_VERSION_HEX >= 0x02060000
199 , 0 // tp_version_tag
200#endif
201#if PY_VERSION_HEX >= 0x03040000
202 , 0 // tp_finalize
203#endif
204#if PY_VERSION_HEX >= 0x03080000
205 , 0 // tp_vectorcall
206#endif
207#if PY_VERSION_HEX >= 0x030c0000
208 , 0 // tp_watched
209#endif
210#if PY_VERSION_HEX >= 0x030d0000
211 , 0 // tp_versions_used
212#endif
213};
214
215namespace {
216
217struct {
220
221struct {
224
225// TODO: refactor with Converters.cxx
226struct CPyCppyy_tagCDataObject { // non-public (but stable)
228 char* b_ptr;
229 int b_needsfree;
230};
231
232} // unnamed namespace
233
234namespace CPyCppyy {
235 PyObject* gThisModule = nullptr;
237 PyObject* gNullPtrObject = nullptr;
243 std::set<Cppyy::TCppType_t> gPinnedTypes;
244 std::ostringstream gCapturedError;
245 std::streambuf* gOldErrorBuffer = nullptr;
246
247 std::map<std::string, std::vector<PyObject*>> &pythonizations()
248 {
249 static std::map<std::string, std::vector<PyObject*>> pyzMap;
250 return pyzMap;
251 }
252}
253
254
255//- private helpers ------------------------------------------------------------
256namespace {
257
258using namespace CPyCppyy;
259
260
261//----------------------------------------------------------------------------
262#if PY_VERSION_HEX < 0x030b0000
263namespace {
264
265class GblGetter {
266public:
267 GblGetter() {
268 PyObject* cppyy = PyImport_AddModule((char*)"cppyy");
269 fGbl = PyObject_GetAttrString(cppyy, (char*)"gbl");
270 }
271 ~GblGetter() { Py_DECREF(fGbl); }
272
273 PyObject* operator*() { return fGbl; }
274
275private:
276 PyObject* fGbl;
277};
278
279} // unnamed namespace
280
281#if PY_VERSION_HEX >= 0x03060000
284{
285 return (*gDictLookupOrg)(mp, key, hash, value_addr, hashpos);
286}
287#define CPYCPPYY_ORGDICT_LOOKUP(mp, key, hash, value_addr, hashpos) \
288 OrgDictLookup(mp, key, hash, value_addr, hashpos)
289
292
293#elif PY_VERSION_HEX >= 0x03030000
296{
297 return (*gDictLookupOrg)(mp, key, hash, value_addr);
298}
299
300#define CPYCPPYY_ORGDICT_LOOKUP(mp, key, hash, value_addr, hashpos) \
301 OrgDictLookup(mp, key, hash, value_addr)
302
305
306#else /* < 3.3 */
307
309{
310 return (*gDictLookupOrg)(mp, key, hash);
311}
312
313#define CPYCPPYY_ORGDICT_LOOKUP(mp, key, hash, value_addr, hashpos) \
314 OrgDictLookup(mp, key, hash)
315
317#endif
318{
319 static GblGetter gbl;
320#if PY_VERSION_HEX >= 0x03060000
322#else
324#endif
325
326// first search dictionary itself
329 return ep;
330
331#if PY_VERSION_HEX >= 0x03060000
332 if (ep >= 0)
333#else
334 if (!ep || (ep->me_key && ep->me_value))
335#endif
336 return ep;
337
338// filter for builtins
339 if (PyDict_GetItem(PyEval_GetBuiltins(), key) != 0)
340 return ep;
341
342// normal lookup failed, attempt to get C++ enum/global/class from top-level
343 gDictLookupActive = true;
344
345// attempt to get C++ enum/global/class from top-level
346 PyObject* val = PyObject_GetAttr(*gbl, key);
347
348 if (val) {
349 // success ...
350
351 if (CPPDataMember_CheckExact(val)) {
352 // don't want to add to dictionary (the proper place would be the
353 // dictionary of the (meta)class), but modifying ep will be noticed no
354 // matter what; just return the actual value and live with the copy in
355 // the dictionary (mostly, this is correct)
356 PyObject* actual_val = Py_TYPE(val)->tp_descr_get(val, nullptr, nullptr);
357 Py_DECREF(val);
358 val = actual_val;
359 }
360
361 // add reference to C++ entity in the given dictionary
362 CPYCPPYY_GET_DICT_LOOKUP(mp) = gDictLookupOrg; // prevent recursion
363 if (PyDict_SetItem((PyObject*)mp, key, val) == 0) {
365 } else {
366#if PY_VERSION_HEX >= 0x03060000
367 ep = -1;
368#else
369 ep->me_key = nullptr;
370 ep->me_value = nullptr;
371#endif
372 }
374
375 // done with val
376 Py_DECREF(val);
377 } else
378 PyErr_Clear();
379
380#if PY_VERSION_HEX >= 0x03030000
381 if (mp->ma_keys->dk_usable <= 0) {
382 // big risk that this lookup will result in a resize, so force it here
383 // to be able to reset the lookup function; of course, this is nowhere
384 // near fool-proof, but should cover interactive usage ...
386 const int maxinsert = 5;
387 PyObject* buf[maxinsert];
388 for (int varmax = 1; varmax <= maxinsert; ++varmax) {
389 for (int ivar = 0; ivar < varmax; ++ivar) {
390 buf[ivar] = CPyCppyy_PyText_FromFormat("__CPYCPPYY_FORCE_RESIZE_%d", ivar);
392 }
393 for (int ivar = 0; ivar < varmax; ++ivar) {
395 Py_DECREF(buf[ivar]);
396 }
397 if (0 < mp->ma_keys->dk_usable)
398 break;
399 }
400
401 // make sure the entry pointer is still valid by re-doing the lookup
403
404 // full reset of all lookup functions
407 }
408#endif
409
410// stopped calling into the reflection system
411 gDictLookupActive = false;
412 return ep;
413}
414
415#endif // PY_VERSION_HEX < 0x030b0000
416
417//----------------------------------------------------------------------------
419{
420#if PY_VERSION_HEX < 0x030b0000
421// Modify the given dictionary to install the lookup function that also
422// tries the global C++ namespace before failing. Called on a module's dictionary,
423// this allows for lazy lookups. This works fine for p3.2 and earlier, but should
424// not be used beyond interactive code for p3.3 and later b/c resizing causes the
425// lookup function to revert to the default (lookdict_unicode_nodummy).
426 PyDictObject* dict = nullptr;
427 if (!PyArg_ParseTuple(args, const_cast<char*>("O!"), &PyDict_Type, &dict))
428 return nullptr;
429
431#else
432// As of py3.11, there is no longer a lookup function pointer in the dict object
433// to replace. Since this feature is not widely advertised, it's simply dropped
434 PyErr_Warn(PyExc_RuntimeWarning, (char*)"lazy lookup is no longer supported");
435 (void)args; // avoid warning about unused parameter
436#endif
437
439}
440
441//----------------------------------------------------------------------------
443{
444// Create a binding for a templated class instantiation.
445
446// args is class name + template arguments; build full instantiation
448 if (nArgs < 2) {
449 PyErr_Format(PyExc_TypeError, "too few arguments for template instantiation");
450 return nullptr;
451 }
452
453// build "< type, type, ... >" part of class name (modifies pyname)
454 const std::string& tmpl_name =
456 if (!tmpl_name.size())
457 return nullptr;
458
460}
461
462//----------------------------------------------------------------------------
463static char* GCIA_kwlist[] = {(char*)"instance", (char*)"field", (char*)"byref", NULL};
464static void* GetCPPInstanceAddress(const char* fname, PyObject* args, PyObject* kwds)
465{
466// Helper to get the address (address-of-address) of various object proxy types.
467 CPPInstance* pyobj = 0; PyObject* pyname = 0; int byref = 0;
468 if (PyArg_ParseTupleAndKeywords(args, kwds, const_cast<char*>("O|O!b"), GCIA_kwlist,
470
472 if (pyname != 0) {
473 // locate property proxy for offset info
474 CPPDataMember* pyprop = nullptr;
475
479 Py_DECREF(dict);
480
482 // this is an address of a value (i.e. &myobj->prop)
483 void* addr = (void*)pyprop->GetAddress(pyobj);
485 return addr;
486 }
487
489
491 "%s is not a valid data member", CPyCppyy_PyText_AsString(pyname));
492 return nullptr;
493 }
494
495 // this is an address of an address (i.e. &myobj, with myobj of type MyObj*)
496 // note that the return result may be null
497 if (!byref) return ((CPPInstance*)pyobj)->GetObject();
498 return &((CPPInstance*)pyobj)->GetObjectRaw();
499
500 } else if (CPyCppyy_PyText_Check(pyobj)) {
501 // special cases for access to the CPyCppyy API
503 if (req == "Instance_AsVoidPtr")
504 return (void*)&Instance_AsVoidPtr;
505 else if (req == "Instance_FromVoidPtr")
506 return (void*)&Instance_FromVoidPtr;
507 }
508 }
509
510 if (!PyErr_Occurred())
511 PyErr_Format(PyExc_ValueError, "invalid argument for %s", fname);
512 return nullptr;
513}
514
515//----------------------------------------------------------------------------
516static PyObject* addressof(PyObject* /* dummy */, PyObject* args, PyObject* kwds)
517{
518// Return object proxy address as a value (cppyy-style), or the same for an array.
519 void* addr = GetCPPInstanceAddress("addressof", args, kwds);
520 if (addr)
521 return PyLong_FromLongLong((intptr_t)addr);
522 else if (!PyErr_Occurred()) {
523 return PyLong_FromLong(0);
524 } else if (PyTuple_CheckExact(args) && PyTuple_GET_SIZE(args) == 1) {
525 PyErr_Clear();
526 PyObject* arg0 = PyTuple_GET_ITEM(args, 0);
527
528 // nullptr special case
529 if (arg0 == gNullPtrObject || (PyInt_Check(arg0) && PyInt_AsLong(arg0) == 0))
530 return PyLong_FromLong(0);
531
532 // overload if unambiguous
534 const auto& methods = ((CPPOverload*)arg0)->fMethodInfo->fMethods;
535 if (methods.size() != 1) {
536 PyErr_SetString(PyExc_TypeError, "overload is not unambiguous");
537 return nullptr;
538 }
539
540 Cppyy::TCppFuncAddr_t caddr = methods[0]->GetFunctionAddress();
541 return PyLong_FromLongLong((intptr_t)caddr);
542 }
543
544 // C functions (incl. ourselves)
545 if (PyCFunction_Check(arg0)) {
546 void* caddr = (void*)PyCFunction_GetFunction(arg0);
547 return PyLong_FromLongLong((intptr_t)caddr);
548 }
549
550 // final attempt: any type of buffer
551 Utility::GetBuffer(arg0, '*', 1, addr, false);
552 if (addr) return PyLong_FromLongLong((intptr_t)addr);
553 }
554
555// error message if not already set
556 if (!PyErr_Occurred()) {
557 if (PyTuple_CheckExact(args) && PyTuple_GET_SIZE(args)) {
558 PyObject* str = PyObject_Str(PyTuple_GET_ITEM(args, 0));
559 if (str && CPyCppyy_PyText_Check(str))
560 PyErr_Format(PyExc_TypeError, "unknown object %s", CPyCppyy_PyText_AsString(str));
561 else
562 PyErr_Format(PyExc_TypeError, "unknown object at %p", (void*)PyTuple_GET_ITEM(args, 0));
563 Py_XDECREF(str);
564 }
565 }
566 return nullptr;
567}
568
569//----------------------------------------------------------------------------
570static PyObject* AsCObject(PyObject* /* unused */, PyObject* args, PyObject* kwds)
571{
572// Return object proxy as an opaque CObject.
573 void* addr = GetCPPInstanceAddress("as_cobject", args, kwds);
574 if (addr)
575 return CPyCppyy_PyCapsule_New((void*)addr, nullptr, nullptr);
576 return nullptr;
577}
578
579//----------------------------------------------------------------------------
580static PyObject* AsCapsule(PyObject* /* unused */, PyObject* args, PyObject* kwds)
581{
582// Return object proxy as an opaque PyCapsule.
583 void* addr = GetCPPInstanceAddress("as_capsule", args, kwds);
584 if (addr)
585#if PY_VERSION_HEX < 0x02060000
586 return PyCObject_FromVoidPtr(addr, nullptr);
587#else
588 return PyCapsule_New(addr, nullptr, nullptr);
589#endif
590 return nullptr;
591}
592
593//----------------------------------------------------------------------------
594static PyObject* AsCTypes(PyObject* /* unused */, PyObject* args, PyObject* kwds)
595{
596// Return object proxy as a ctypes c_void_p
597 void* addr = GetCPPInstanceAddress("as_ctypes", args, kwds);
598 if (!addr)
599 return nullptr;
600
601// TODO: refactor code below with converters code
602 static PyTypeObject* ct_cvoidp = nullptr;
603 if (!ct_cvoidp) {
604 PyObject* ctmod = PyImport_ImportModule("ctypes"); // ref-count kept
605 if (!ctmod) return nullptr;
606
609 if (!ct_cvoidp) return nullptr;
610 Py_DECREF(ct_cvoidp); // module keeps a reference
611 }
612
613 PyObject* ref = ct_cvoidp->tp_new(ct_cvoidp, nullptr, nullptr);
614 *(void**)((CPyCppyy_tagCDataObject*)ref)->b_ptr = addr;
615 ((CPyCppyy_tagCDataObject*)ref)->b_needsfree = 0;
616 return ref;
617}
618
619//----------------------------------------------------------------------------
620static PyObject* AsMemoryView(PyObject* /* unused */, PyObject* pyobject)
621{
622// Return a raw memory view on arrays of PODs.
624 PyErr_SetString(PyExc_TypeError, "C++ object proxy expected");
625 return nullptr;
626 }
627
630
631 Py_ssize_t array_len = pyobj->ArrayLength();
632
633 if (array_len < 0 || !Cppyy::IsAggregate(klass)) {
635 PyExc_TypeError, "object is not a proxy to an array of PODs of known size");
636 return nullptr;
637 }
638
639 Py_buffer view;
640
641 view.obj = pyobject;
642 view.buf = pyobj->GetObject();
643 view.itemsize = Cppyy::SizeOf(klass);
644 view.len = view.itemsize * array_len;
645 view.readonly = 0;
646 view.format = NULL; // i.e. "B" assumed
647 view.ndim = 1;
648 view.shape = NULL;
649 view.strides = NULL;
650 view.suboffsets = NULL;
651 view.internal = NULL;
652
653 return PyMemoryView_FromBuffer(&view);
654}
655
656//----------------------------------------------------------------------------
658{
659// From a long representing an address or a PyCapsule/CObject, bind to a class.
661 if (argc != 2) {
663 "bind_object takes 2 positional arguments but (" PY_SSIZE_T_FORMAT " were given)", argc);
664 return nullptr;
665 }
666
667// convert 2nd argument first (used for both pointer value and instance cases)
669 PyObject* arg1 = PyTuple_GET_ITEM(args, 1);
670 if (!CPyCppyy_PyText_Check(arg1)) { // not string, then class
671 if (CPPScope_Check(arg1))
672 cast_type = ((CPPClass*)arg1)->fCppType;
673 else
675 } else
677
678 if (!cast_type && arg1) {
681 }
682
683 if (!cast_type) {
685 "bind_object expects a valid class or class name as an argument");
686 return nullptr;
687 }
688
689// next, convert the first argument, some pointer value or a pre-existing instance
690 PyObject* arg0 = PyTuple_GET_ITEM(args, 0);
691
692 if (CPPInstance_Check(arg0)) {
693 // if this instance's class has a relation to the requested one, calculate the
694 // offset, erase if from any caches, and update the pointer and type
696 Cppyy::TCppType_t cur_type = arg0_pyobj->ObjectIsA(false /* check_smart */);
697
698 bool isPython = CPPScope_Check(arg1) && \
699 (((CPPClass*)arg1)->fFlags & CPPScope::kIsPython);
700
701 if (cur_type == cast_type && !isPython) {
702 Py_INCREF(arg0); // nothing to do
703 return arg0;
704 }
705
706 int direction = 0;
707 Cppyy::TCppType_t base = 0, derived = 0;
710 base = cur_type;
711 direction = -1; // down-cast
712 } else if (Cppyy::IsSubtype(cur_type, cast_type)) {
713 base = cast_type;
715 direction = 1; // up-cast
716 } else {
718 "provided instance and provided target type are unrelated");
719 return nullptr;
720 }
721
722 Cppyy::TCppObject_t address = (Cppyy::TCppObject_t)arg0_pyobj->GetObject();
723 ptrdiff_t offset = Cppyy::GetBaseOffset(derived, base, address, direction);
724
725 // it's debatable whether a new proxy should be created rather than updating
726 // the old, but changing the old object would be changing the behavior of all
727 // code that has a reference to it, which may not be the intention if the cast
728 // is on a C++ data member; this probably is the "least surprise" option
729
730 // ownership is taken over as needed, again following the principle of "least
731 // surprise" as most likely only the cast object will be retained
732 bool owns = arg0_pyobj->fFlags & CPPInstance::kIsOwner;
733
734 if (!isPython) {
735 // ordinary C++ class
737 (void*)((intptr_t)address + offset), cast_type, owns ? CPPInstance::kIsOwner : 0);
738 if (owns && pyobj) arg0_pyobj->CppOwns();
739 return pyobj;
740
741 } else {
742 // rebinding to a Python-side class, create a fresh instance first to be able to
743 // perform a lookup of the original dispatch object and if found, return original
744 void* cast_address = (void*)((intptr_t)address + offset);
745 PyObject* pyobj = ((PyTypeObject*)arg1)->tp_new((PyTypeObject*)arg1, nullptr, nullptr);
746 ((CPPInstance*)pyobj)->GetObjectRaw() = cast_address;
747
750 /* Note: the resultant object is borrowed */
751 if (CPPInstance_Check(res) && ((CPPInstance*)res)->GetObject() == cast_address) {
752 ((CPPInstance*)pyobj)->CppOwns(); // make sure C++ object isn't deleted
753 Py_DECREF(pyobj); // on DECREF (is default, but still)
754 pyobj = res;
755 } else {
756 if (res) Py_DECREF(res); // most likely Py_None
757 else PyErr_Clear(); // should not happen
758 }
760
761 if (pyobj && owns) {
762 arg0_pyobj->CppOwns();
763 ((CPPInstance*)pyobj)->PythonOwns();
764 }
765
766 return pyobj;
767 }
768 }
769
770// not a pre-existing object; get the address and bind
771 void* addr = nullptr;
772 if (arg0 != gNullPtrObject) {
774 if (PyErr_Occurred()) {
775 PyErr_Clear();
776
778 if (PyErr_Occurred()) {
779 PyErr_Clear();
780
781 // last chance, perhaps it's a buffer/array (return from void*)
782 Py_ssize_t buflen = Utility::GetBuffer(PyTuple_GetItem(args, 0), '*', 1, addr, false);
783 if (!addr || !buflen) {
785 "bind_object requires a CObject/Capsule, long integer, buffer, or instance as first argument");
786 return nullptr;
787 }
788 }
789 }
790 }
791
792 bool do_cast = false;
793 if (kwds) {
796 }
797
798 if (do_cast)
800
802}
803
804//----------------------------------------------------------------------------
805static PyObject* Move(PyObject*, PyObject* pyobject)
806{
807// Prepare the given C++ object for moving.
809 PyErr_SetString(PyExc_TypeError, "C++ object expected");
810 return nullptr;
811 }
812
815 return pyobject;
816}
817
818
819//----------------------------------------------------------------------------
821{
822// Remove a previously registered pythonizor from the given scope.
823 PyObject* pythonizor = nullptr; const char* scope;
824 if (!PyArg_ParseTuple(args, const_cast<char*>("Os"), &pythonizor, &scope))
825 return nullptr;
826
830 "given \'%s\' object is not callable", CPyCppyy_PyText_AsString(pystr));
832 return nullptr;
833 }
834
836 pythonizations()[scope].push_back(pythonizor);
837
839}
840
841
842//----------------------------------------------------------------------------
844{
845// Remove a previously registered pythonizor from the given scope.
846 PyObject* pythonizor = nullptr; const char* scope;
847 if (!PyArg_ParseTuple(args, const_cast<char*>("Os"), &pythonizor, &scope))
848 return nullptr;
849
850 auto &pyzMap = pythonizations();
851 auto p1 = pyzMap.find(scope);
852 if (p1 != pyzMap.end()) {
853 auto p2 = std::find(p1->second.begin(), p1->second.end(), pythonizor);
854 if (p2 != p1->second.end()) {
855 p1->second.erase(p2);
857 }
858 }
859
861}
862
863//----------------------------------------------------------------------------
865{
866// Add a pinning so that objects of type `derived' are interpreted as
867// objects of type `base'.
868 if (!CPPScope_Check(pyclass)) {
869 PyErr_SetString(PyExc_TypeError, "C++ class expected");
870 return nullptr;
871 }
872
873 gPinnedTypes.insert(((CPPClass*)pyclass)->fCppType);
874
876}
877
878//----------------------------------------------------------------------------
880{
881// Add a type reducer to map type2 to type2 on function returns.
882 const char *reducable, *reduced;
883 if (!PyArg_ParseTuple(args, const_cast<char*>("ss"), &reducable, &reduced))
884 return nullptr;
885
887
889}
890
891//----------------------------------------------------------------------------
892static PyObject* SetMemoryPolicy(PyObject*, PyObject* args)
893{
894// Set the global memory policy, which affects object ownership when objects
895// are passed as function arguments.
896 PyObject* policy = nullptr;
897 if (!PyArg_ParseTuple(args, const_cast<char*>("O!"), &PyInt_Type, &policy))
898 return nullptr;
899
900 long old = (long)CallContext::sMemoryPolicy;
901
902 long l = PyInt_AS_LONG(policy);
904 return PyInt_FromLong(old);
905 }
906
907 PyErr_Format(PyExc_ValueError, "Unknown policy %ld", l);
908 return nullptr;
909}
910
911//----------------------------------------------------------------------------
912static PyObject* SetGlobalSignalPolicy(PyObject*, PyObject* args)
913{
914// Set the global signal policy, which determines whether a jmp address
915// should be saved to return to after a C++ segfault.
917 if (!PyArg_ParseTuple(args, const_cast<char*>("O"), &setProtected))
918 return nullptr;
919
922 }
923
925}
926
927//----------------------------------------------------------------------------
928static PyObject* SetOwnership(PyObject*, PyObject* args)
929{
930// Set the ownership (True is python-owns) for the given object.
931 CPPInstance* pyobj = nullptr; PyObject* pykeep = nullptr;
932 if (!PyArg_ParseTuple(args, const_cast<char*>("O!O!"),
934 return nullptr;
935
936 (bool)PyLong_AsLong(pykeep) ? pyobj->PythonOwns() : pyobj->CppOwns();
937
939}
940
941//----------------------------------------------------------------------------
943{
944// Add a smart pointer to the list of known smart pointer types.
945 const char* type_name;
946 if (!PyArg_ParseTuple(args, const_cast<char*>("s"), &type_name))
947 return nullptr;
948
950
952}
953
954//----------------------------------------------------------------------------
956{
957 gOldErrorBuffer = std::cerr.rdbuf();
958 std::cerr.rdbuf(gCapturedError.rdbuf());
959
961}
962
963//----------------------------------------------------------------------------
965{
966// restore old rdbuf and return captured result
967 std::cerr.rdbuf(gOldErrorBuffer);
968 gOldErrorBuffer = nullptr;
969
970 std::string capturedError = std::move(gCapturedError).str();
971
972 gCapturedError.str("");
973 gCapturedError.clear();
974
975 return Py_BuildValue("s", capturedError.c_str());
976}
977} // unnamed namespace
978
979
980//- data -----------------------------------------------------------------------
982 {(char*) "CreateScopeProxy", (PyCFunction)CPyCppyy::CreateScopeProxy,
983 METH_VARARGS, (char*)"cppyy internal function"},
984 {(char*) "MakeCppTemplateClass", (PyCFunction)MakeCppTemplateClass,
985 METH_VARARGS, (char*)"cppyy internal function"},
986 {(char*) "_set_cpp_lazy_lookup", (PyCFunction)SetCppLazyLookup,
987 METH_VARARGS, (char*)"cppyy internal function"},
988 {(char*) "_DestroyPyStrings", (PyCFunction)CPyCppyy::DestroyPyStrings,
989 METH_NOARGS, (char*)"cppyy internal function"},
990 {(char*) "addressof", (PyCFunction)addressof,
991 METH_VARARGS | METH_KEYWORDS, (char*)"Retrieve address of proxied object or field as a value."},
992 {(char*) "as_cobject", (PyCFunction)AsCObject,
993 METH_VARARGS | METH_KEYWORDS, (char*)"Retrieve address of proxied object or field in a CObject."},
994 {(char*) "as_capsule", (PyCFunction)AsCapsule,
995 METH_VARARGS | METH_KEYWORDS, (char*)"Retrieve address of proxied object or field in a PyCapsule."},
996 {(char*) "as_ctypes", (PyCFunction)AsCTypes,
997 METH_VARARGS | METH_KEYWORDS, (char*)"Retrieve address of proxied object or field in a ctypes c_void_p."},
998 {(char*) "as_memoryview", (PyCFunction)AsMemoryView,
999 METH_O, (char*)"Represent an array of objects as raw memory."},
1000 {(char*)"bind_object", (PyCFunction)BindObject,
1001 METH_VARARGS | METH_KEYWORDS, (char*) "Create an object of given type, from given address."},
1002 {(char*) "move", (PyCFunction)Move,
1003 METH_O, (char*)"Cast the C++ object to become movable."},
1004 {(char*) "add_pythonization", (PyCFunction)AddPythonization,
1005 METH_VARARGS, (char*)"Add a pythonizor."},
1006 {(char*) "remove_pythonization", (PyCFunction)RemovePythonization,
1007 METH_VARARGS, (char*)"Remove a pythonizor."},
1008 {(char*) "_pin_type", (PyCFunction)PinType,
1009 METH_O, (char*)"Install a type pinning."},
1010 {(char*) "_add_type_reducer", (PyCFunction)AddTypeReducer,
1011 METH_VARARGS, (char*)"Add a type reducer."},
1012 {(char*) "SetMemoryPolicy", (PyCFunction)SetMemoryPolicy,
1013 METH_VARARGS, (char*)"Determines object ownership model."},
1014 {(char*) "SetGlobalSignalPolicy", (PyCFunction)SetGlobalSignalPolicy,
1015 METH_VARARGS, (char*)"Trap signals in safe mode to prevent interpreter abort."},
1016 {(char*) "SetOwnership", (PyCFunction)SetOwnership,
1017 METH_VARARGS, (char*)"Modify held C++ object ownership."},
1018 {(char*) "AddSmartPtrType", (PyCFunction)AddSmartPtrType,
1019 METH_VARARGS, (char*) "Add a smart pointer to the list of known smart pointer types."},
1020 {(char*) "_begin_capture_stderr", (PyCFunction)BeginCaptureStderr,
1021 METH_NOARGS, (char*) "Begin capturing stderr to a in memory buffer."},
1022 {(char*) "_end_capture_stderr", (PyCFunction)EndCaptureStderr,
1023 METH_NOARGS, (char*) "End capturing stderr and returns the captured buffer."},
1024 {nullptr, nullptr, 0, nullptr}
1025};
1026
1027
1028#if PY_VERSION_HEX >= 0x03000000
1029struct module_state {
1030 PyObject *error;
1031};
1032
1033#define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
1034
1035static int cpycppyymodule_traverse(PyObject* m, visitproc visit, void* arg)
1036{
1037 Py_VISIT(GETSTATE(m)->error);
1038 return 0;
1039}
1040
1041static int cpycppyymodule_clear(PyObject* m)
1042{
1043 Py_CLEAR(GETSTATE(m)->error);
1044 return 0;
1045}
1046
1047
1048static struct PyModuleDef moduledef = {
1050 "libcppyy",
1051 nullptr,
1052 sizeof(struct module_state),
1054 nullptr,
1057 nullptr
1058};
1059
1060
1061//----------------------------------------------------------------------------
1062#define CPYCPPYY_INIT_ERROR return nullptr
1063extern "C" PyObject* PyInit_libcppyy()
1064#else
1065#define CPYCPPYY_INIT_ERROR return
1066extern "C" void initlibcppyy()
1067#endif
1068{
1069// Initialization of extension module libcppyy.
1070
1071// load commonly used python strings
1074
1075// setup interpreter
1076#if PY_VERSION_HEX < 0x03090000
1078#endif
1079
1080#if PY_VERSION_HEX < 0x030b0000
1081// prepare for laziness (the insert is needed to capture the most generic lookup
1082// function, just in case ...)
1083 PyObject* dict = PyDict_New();
1087#if PY_VERSION_HEX >= 0x03030000
1088 gDictLookupOrg = (dict_lookup_func)((PyDictObject*)dict)->ma_keys->dk_lookup;
1089#else
1091#endif
1092 Py_DECREF(dict);
1093#endif // PY_VERSION_HEX < 0x030b0000
1094
1095// setup this module
1096#if PY_VERSION_HEX >= 0x03000000
1098#else
1099 gThisModule = Py_InitModule(const_cast<char*>("libcppyy"), gCPyCppyyMethods);
1100#endif
1101 if (!gThisModule)
1103
1104// keep gThisModule, but do not increase its reference count even as it is borrowed,
1105// or a self-referencing cycle would be created
1106
1107// external types
1109 PyModule_AddObject(gThisModule, "type_map", gPyTypeMap); // steals reference
1110
1111// Pythonizations ...
1112 PyModule_AddObject(gThisModule, "UserExceptions", PyDict_New());
1113
1114// inject meta type
1115 if (!Utility::InitProxy(gThisModule, &CPPScope_Type, "CPPScope"))
1117
1118// inject object proxy type
1119 if (!Utility::InitProxy(gThisModule, &CPPInstance_Type, "CPPInstance"))
1121
1122// inject exception object proxy type
1123 if (!Utility::InitProxy(gThisModule, &CPPExcInstance_Type, "CPPExcInstance"))
1125
1126// inject method proxy type
1127 if (!Utility::InitProxy(gThisModule, &CPPOverload_Type, "CPPOverload"))
1129
1130// inject template proxy type
1131 if (!Utility::InitProxy(gThisModule, &TemplateProxy_Type, "TemplateProxy"))
1133
1134// inject property proxy type
1135 if (!Utility::InitProxy(gThisModule, &CPPDataMember_Type, "CPPDataMember"))
1137
1138// inject custom data types
1139#if PY_VERSION_HEX < 0x03000000
1142
1145#endif
1146
1149
1150 if (!Utility::InitProxy(gThisModule, &TupleOfInstances_Type, "InstanceArray"))
1152
1153 if (!Utility::InitProxy(gThisModule, &LowLevelView_Type, "LowLevelView"))
1155
1156 if (!Utility::InitProxy(gThisModule, &PyNullPtr_t_Type, "nullptr_t"))
1158
1159// custom iterators
1162
1163 if (PyType_Ready(&IndexIter_Type) < 0)
1165
1166 if (PyType_Ready(&VectorIter_Type) < 0)
1168
1169// inject identifiable nullptr and default
1172 PyModule_AddObject(gThisModule, (char*)"nullptr", gNullPtrObject);
1173
1176 PyModule_AddObject(gThisModule, (char*)"default", gDefaultObject);
1177
1178// C++-specific exceptions
1179 PyObject* cppfatal = PyErr_NewException((char*)"cppyy.ll.FatalError", nullptr, nullptr);
1180 PyModule_AddObject(gThisModule, (char*)"FatalError", cppfatal);
1181
1182 gBusException = PyErr_NewException((char*)"cppyy.ll.BusError", cppfatal, nullptr);
1183 PyModule_AddObject(gThisModule, (char*)"BusError", gBusException);
1184 gSegvException = PyErr_NewException((char*)"cppyy.ll.SegmentationViolation", cppfatal, nullptr);
1185 PyModule_AddObject(gThisModule, (char*)"SegmentationViolation", gSegvException);
1186 gIllException = PyErr_NewException((char*)"cppyy.ll.IllegalInstruction", cppfatal, nullptr);
1187 PyModule_AddObject(gThisModule, (char*)"IllegalInstruction", gIllException);
1188 gAbrtException = PyErr_NewException((char*)"cppyy.ll.AbortSignal", cppfatal, nullptr);
1189 PyModule_AddObject(gThisModule, (char*)"AbortSignal", gAbrtException);
1190
1191// policy labels
1192 PyModule_AddObject(gThisModule, (char*)"kMemoryHeuristics",
1194 PyModule_AddObject(gThisModule, (char*)"kMemoryStrict",
1196
1197// gbl namespace is injected in cppyy.py
1198
1199// create the memory regulator
1201
1202#if PY_VERSION_HEX >= 0x03000000
1204 return gThisModule;
1205#endif
1206}
static PyObject * default_repr(PyObject *)
#define CPYCPPYY_ORGDICT_LOOKUP(mp, key, hash, value_addr, hashpos)
static PyObject * nullptr_repr(PyObject *)
static PyNumberMethods nullptr_as_number
#define CPYCPPYY_INIT_ERROR
static void default_dealloc(PyObject *)
void initlibcppyy()
static PyTypeObject PyDefault_t_Type
static void nullptr_dealloc(PyObject *)
static int nullptr_nonzero(PyObject *)
static PyMethodDef gCPyCppyyMethods[]
static PyTypeObject PyNullPtr_t_Type
#define CPYCPPYY_GET_DICT_LOOKUP(mp)
#define Py_TYPE(ob)
Definition CPyCppyy.h:196
PyDictEntry *(* dict_lookup_func)(PyDictObject *, PyObject *, long)
Definition CPyCppyy.h:44
#define Py_RETURN_TRUE
Definition CPyCppyy.h:272
#define Py_RETURN_FALSE
Definition CPyCppyy.h:276
#define PY_SSIZE_T_FORMAT
Definition CPyCppyy.h:218
static void * CPyCppyy_PyCapsule_GetPointer(PyObject *capsule, const char *)
Definition CPyCppyy.h:104
#define CPyCppyy_PyText_AsString
Definition CPyCppyy.h:76
static PyObject * CPyCppyy_PyCapsule_New(void *cobj, const char *, void(*destr)(void *))
Definition CPyCppyy.h:98
long Py_hash_t
Definition CPyCppyy.h:114
static PyObject * PyObject_CallMethodOneArg(PyObject *obj, PyObject *name, PyObject *arg)
Definition CPyCppyy.h:385
#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 CPyCppyy_PyText_Check
Definition CPyCppyy.h:74
#define PyVarObject_HEAD_INIT(type, size)
Definition CPyCppyy.h:194
_object PyObject
static struct PyModuleDef moduledef
#define GETSTATE(m)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
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
TTime operator*(const TTime &t1, const TTime &t2)
Definition TTime.h:85
const_iterator begin() const
const_iterator end() const
PyObject * gDispGet
Definition PyStrings.cxx:70
Py_ssize_t GetBuffer(PyObject *pyobject, char tc, int size, void *&buf, bool check=true)
Definition Utility.cxx:813
std::string ConstructTemplateArgs(PyObject *pyname, PyObject *tpArgs, PyObject *args=nullptr, ArgPreference=kNone, int argoff=0, int *pcnt=nullptr)
Definition Utility.cxx:585
bool InitProxy(PyObject *module, PyTypeObject *pytype, const char *name)
Definition Utility.cxx:793
PyTypeObject CPPInstance_Type
PyObject * gAbrtException
PyObject * gDefaultObject
bool gDictLookupActive
Definition Utility.cxx:28
PyTypeObject VectorIter_Type
PyTypeObject CPPExcInstance_Type
PyObject * GetScopeProxy(Cppyy::TCppScope_t)
std::ostringstream gCapturedError
dict_lookup_func gDictLookupOrg
Definition Utility.cxx:27
PyTypeObject CustomInstanceMethod_Type
PyObject * CreateScopeProxy(Cppyy::TCppScope_t, const unsigned flags=0)
bool CPPDataMember_CheckExact(T *object)
PyTypeObject RefFloat_Type
Custom "builtins," detectable by type, for pass by ref and improved performance.
PyObject * gSegvException
std::set< Cppyy::TCppType_t > gPinnedTypes
PyObject * DestroyPyStrings()
PyObject * BindCppObjectNoCast(Cppyy::TCppObject_t object, Cppyy::TCppType_t klass, const unsigned flags=0)
std::map< std::string, std::vector< PyObject * > > & pythonizations()
bool CPPScope_Check(T *object)
Definition CPPScope.h:81
bool CreatePyStrings()
Definition PyStrings.cxx:85
CPYCPPYY_EXTERN PyObject * Instance_FromVoidPtr(void *addr, const std::string &classname, bool python_owns=false)
Definition API.cxx:121
bool CPPInstance_Check(T *object)
PyTypeObject IndexIter_Type
PyObject * gNullPtrObject
PyTypeObject CPPOverload_Type
PyTypeObject TemplateProxy_Type
PyObject * gThisModule
Definition CPPMethod.cxx:30
PyTypeObject InstanceArrayIter_Type
bool CPPDataMember_Check(T *object)
PyObject * BindCppObject(Cppyy::TCppObject_t object, Cppyy::TCppType_t klass, const unsigned flags=0)
CPYCPPYY_EXTERN void * Instance_AsVoidPtr(PyObject *pyobject)
Definition API.cxx:106
PyTypeObject CPPScope_Type
Definition CPPScope.cxx:646
PyObject * gIllException
PyTypeObject LowLevelView_Type
PyObject * gPyTypeMap
bool CPPOverload_CheckExact(T *object)
Definition CPPOverload.h:96
PyTypeObject CPPDataMember_Type
PyObject * gBusException
std::streambuf * gOldErrorBuffer
PyTypeObject TupleOfInstances_Type
Representation of C-style array of instances.
PyTypeObject RefInt_Type
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 void AddSmartPtrType(const std::string &)
RPY_EXPORTED bool IsSubtype(TCppType_t derived, TCppType_t base)
void * TCppObject_t
Definition cpp_cppyy.h:21
TCppScope_t TCppType_t
Definition cpp_cppyy.h:19
RPY_EXPORTED void AddTypeReducer(const std::string &reducable, const std::string &reduced)
RPY_EXPORTED bool IsAggregate(TCppType_t type)
RPY_EXPORTED TCppScope_t GetScope(const std::string &scope_name)
void * TCppFuncAddr_t
Definition cpp_cppyy.h:25
static ECallFlags sMemoryPolicy
Definition CallContext.h:78
static bool SetGlobalSignalPolicy(bool setProtected)
static bool SetMemoryPolicy(ECallFlags e)
PyObject_HEAD char * b_ptr
PyObject * error
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4