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