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