Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
Utility.cxx
Go to the documentation of this file.
1// Bindings
2#include "CPyCppyy.h"
3#include "Utility.h"
4#include "CPPFunction.h"
5#include "CPPInstance.h"
6#include "CPPOverload.h"
7#include "ProxyWrappers.h"
8#include "PyCallable.h"
9#include "PyStrings.h"
10#include "CustomPyTypes.h"
11#include "TemplateProxy.h"
12#include "TypeManip.h"
13
14// Standard
15#include <limits.h>
16#include <string.h>
17#include <algorithm>
18#include <list>
19#include <mutex>
20#include <set>
21#include <sstream>
22#include <utility>
23
24
25//- data _____________________________________________________________________
26#if PY_VERSION_HEX < 0x030b0000
29#endif
30
31typedef std::map<std::string, std::string> TC2POperatorMapping_t;
33static std::set<std::string> gOpSkip;
34static std::set<std::string> gOpRemove;
35
36namespace CPyCppyy {
37// special objects
40}
41
42namespace {
43
44 using namespace CPyCppyy::Utility;
45
46 struct InitOperatorMapping_t {
47 public:
48 InitOperatorMapping_t() {
49 // Initialize the global map of operator names C++ -> python.
50
51 gOpSkip.insert("[]"); // __s/getitem__, depends on return type
52 gOpSkip.insert("+"); // __add__, depends on # of args (see __pos__)
53 gOpSkip.insert("-"); // __sub__, id. (eq. __neg__)
54 gOpSkip.insert("*"); // __mul__ or __deref__
55 gOpSkip.insert("++"); // __postinc__ or __preinc__
56 gOpSkip.insert("--"); // __postdec__ or __predec__
57
58 gOpRemove.insert("new"); // this and the following not handled at all
59 gOpRemove.insert("new[]");
60 gOpRemove.insert("delete");
61 gOpRemove.insert("delete[]");
62
63 gC2POperatorMapping["[]"] = "__getitem__";
64 gC2POperatorMapping["()"] = "__call__";
65 gC2POperatorMapping["%"] = "__mod__";
66 gC2POperatorMapping["**"] = "__pow__";
67 gC2POperatorMapping["<<"] = "__lshift__";
68 gC2POperatorMapping[">>"] = "__rshift__";
69 gC2POperatorMapping["&"] = "__and__";
70 gC2POperatorMapping["&&"] = "__dand__";
71 gC2POperatorMapping["|"] = "__or__";
72 gC2POperatorMapping["||"] = "__dor__";
73 gC2POperatorMapping["^"] = "__xor__";
74 gC2POperatorMapping["~"] = "__invert__";
75 gC2POperatorMapping[","] = "__comma__";
76 gC2POperatorMapping["+="] = "__iadd__";
77 gC2POperatorMapping["-="] = "__isub__";
78 gC2POperatorMapping["*="] = "__imul__";
80 gC2POperatorMapping["%="] = "__imod__";
81 gC2POperatorMapping["**="] = "__ipow__";
82 gC2POperatorMapping["<<="] = "__ilshift__";
83 gC2POperatorMapping[">>="] = "__irshift__";
84 gC2POperatorMapping["&="] = "__iand__";
85 gC2POperatorMapping["|="] = "__ior__";
86 gC2POperatorMapping["^="] = "__ixor__";
87 gC2POperatorMapping["=="] = "__eq__";
88 gC2POperatorMapping["!="] = "__ne__";
89 gC2POperatorMapping[">"] = "__gt__";
90 gC2POperatorMapping["<"] = "__lt__";
91 gC2POperatorMapping[">="] = "__ge__";
92 gC2POperatorMapping["<="] = "__le__";
93
94 // the following type mappings are "exact"
95 gC2POperatorMapping["const char*"] = "__str__";
96 gC2POperatorMapping["char*"] = "__str__";
97 gC2POperatorMapping["const char *"] = gC2POperatorMapping["const char*"];
98 gC2POperatorMapping["char *"] = gC2POperatorMapping["char*"];
99 gC2POperatorMapping["int"] = "__int__";
101 gC2POperatorMapping["double"] = "__float__";
102
103 // the following type mappings are "okay"; the assumption is that they
104 // are not mixed up with the ones above or between themselves (and if
105 // they are, that it is done consistently)
106 gC2POperatorMapping["short"] = "__int__";
107 gC2POperatorMapping["unsigned short"] = "__int__";
108 gC2POperatorMapping["unsigned int"] = CPPYY__long__;
109 gC2POperatorMapping["unsigned long"] = CPPYY__long__;
110 gC2POperatorMapping["long long"] = CPPYY__long__;
111 gC2POperatorMapping["unsigned long long"] = CPPYY__long__;
112 gC2POperatorMapping["float"] = "__float__";
113
114 gC2POperatorMapping["->"] = "__follow__"; // not an actual python operator
115 gC2POperatorMapping["="] = "__assign__"; // id.
116
117#if PY_VERSION_HEX < 0x03000000
118 gC2POperatorMapping["bool"] = "__cpp_nonzero__";
119#else
120 gC2POperatorMapping["bool"] = "__cpp_bool__";
121#endif
122 }
123 } initOperatorMapping_;
124
125 inline std::string full_scope(const std::string& tpname) {
126 return tpname[0] == ':' ? tpname : "::"+tpname;
127 }
128
129} // unnamed namespace
130
131
132//- public functions ---------------------------------------------------------
134{
135// Convert <pybject> to C++ unsigned long, with bounds checking, allow int -> ulong.
136 if (PyFloat_Check(pyobject)) {
137 PyErr_SetString(PyExc_TypeError, "can\'t convert float to unsigned long");
138 return (unsigned long)-1;
139 } else if (pyobject == CPyCppyy::gDefaultObject) {
140 return (unsigned long)0;
141 }
142
143 unsigned long ul = PyLong_AsUnsignedLong(pyobject);
144 if (PyErr_Occurred() && PyInt_Check(pyobject)) {
145 PyErr_Clear();
146 long i = PyInt_AS_LONG(pyobject);
147 if (0 <= i) {
148 ul = (unsigned long)i;
149 } else {
150 PyErr_SetString(PyExc_ValueError,
151 "can\'t convert negative value to unsigned long");
152 return (unsigned long)-1;
153 }
154 }
155
156 return ul;
157}
158
159//----------------------------------------------------------------------------
161{
162// Convert <pyobject> to C++ unsigned long long, with bounds checking.
163 if (PyFloat_Check(pyobject)) {
164 PyErr_SetString(PyExc_TypeError, "can\'t convert float to unsigned long long");
165 return -1;
166 } else if (pyobject == CPyCppyy::gDefaultObject) {
167 return (unsigned long)0;
168 }
169
170 PY_ULONG_LONG ull = PyLong_AsUnsignedLongLong(pyobject);
171 if (PyErr_Occurred() && PyInt_Check(pyobject)) {
172 PyErr_Clear();
173 long i = PyInt_AS_LONG(pyobject);
174 if (0 <= i) {
175 ull = (PY_ULONG_LONG)i;
176 } else {
177 PyErr_SetString(PyExc_ValueError,
178 "can\'t convert negative value to unsigned long long");
179 }
180 }
181
182 return ull;
183}
184
185//----------------------------------------------------------------------------
187 PyObject* pyclass, const char* label, PyCFunction cfunc, int flags)
188{
189// Add the given function to the class under name 'label'.
190
191// use list for clean-up (.so's are unloaded only at interpreter shutdown)
192 static std::list<PyMethodDef> s_pymeths;
193
194 s_pymeths.push_back(PyMethodDef());
195 PyMethodDef* pdef = &s_pymeths.back();
196 pdef->ml_name = const_cast<char*>(label);
197 pdef->ml_meth = cfunc;
198 pdef->ml_flags = flags;
199 pdef->ml_doc = nullptr;
200
201 PyObject* func = PyCFunction_New(pdef, nullptr);
203 PyObject* method = CustomInstanceMethod_New(func, nullptr, pyclass);
204 bool isOk = PyType_Type.tp_setattro(pyclass, name, method) == 0;
205 Py_DECREF(method);
206 Py_DECREF(name);
207 Py_DECREF(func);
208
209 if (PyErr_Occurred())
210 return false;
211
212 if (!isOk) {
213 PyErr_Format(PyExc_TypeError, "could not add method %s", label);
214 return false;
215 }
216
217 return true;
218}
219
220//----------------------------------------------------------------------------
221bool CPyCppyy::Utility::AddToClass(PyObject* pyclass, const char* label, const char* func)
222{
223// Add the given function to the class under name 'label'.
224 PyObject* pyfunc = PyObject_GetAttrString(pyclass, const_cast<char*>(func));
225 if (!pyfunc)
226 return false;
227
228 PyObject* pylabel = CPyCppyy_PyText_InternFromString(const_cast<char*>(label));
229 bool isOk = PyType_Type.tp_setattro(pyclass, pylabel, pyfunc) == 0;
230 Py_DECREF(pylabel);
231
232 Py_DECREF(pyfunc);
233 return isOk;
234}
235
236//----------------------------------------------------------------------------
237bool CPyCppyy::Utility::AddToClass(PyObject* pyclass, const char* label, PyCallable* pyfunc)
238{
239// Add the given function to the class under name 'label'.
240 CPPOverload* method =
241 (CPPOverload*)PyObject_GetAttrString(pyclass, const_cast<char*>(label));
242
243 if (!method || !CPPOverload_Check(method)) {
244 // not adding to existing CPPOverload; add callable directly to the class
245 if (PyErr_Occurred())
246 PyErr_Clear();
247 Py_XDECREF((PyObject*)method);
248 method = CPPOverload_New(label, pyfunc);
249 PyObject* pylabel = CPyCppyy_PyText_InternFromString(const_cast<char*>(label));
250 bool isOk = PyType_Type.tp_setattro(pyclass, pylabel, (PyObject*)method) == 0;
251 Py_DECREF(pylabel);
252 Py_DECREF(method);
253 return isOk;
254 }
255
256 method->AdoptMethod(pyfunc);
257
258 Py_DECREF(method);
259 return true;
260}
261
262
263//----------------------------------------------------------------------------
264static inline
265CPyCppyy::PyCallable* BuildOperator(const std::string& lcname, const std::string& rcname,
266 const char* op, Cppyy::TCppScope_t scope, bool reverse=false)
267{
268// Helper to find a function with matching signature in 'funcs'.
269 std::string opname = "operator";
270 opname += op;
271
272 Cppyy::TCppIndex_t idx = Cppyy::GetGlobalOperator(scope, lcname, rcname, opname);
273 if (idx == (Cppyy::TCppIndex_t)-1)
274 return nullptr;
275
276 Cppyy::TCppMethod_t meth = Cppyy::GetMethod(scope, idx);
277 if (!reverse)
278 return new CPyCppyy::CPPFunction(scope, meth);
279 return new CPyCppyy::CPPReverseBinary(scope, meth);
280}
281
282//----------------------------------------------------------------------------
284{
285// Find a callable matching named operator (op) and klass arguments in the global
286// namespace or the klass' namespace.
287
288 if (!CPPScope_Check(pyclass))
289 return nullptr;
290
291 CPPClass* klass = (CPPClass*)pyclass;
292 const std::string& lcname = Cppyy::GetScopedFinalName(klass->fCppType);
293 Cppyy::TCppScope_t scope = Cppyy::GetScope(TypeManip::extract_namespace(lcname));
294 return FindBinaryOperator(lcname, "", op, scope, false);
295}
296
297//----------------------------------------------------------------------------
299 const char* op, Cppyy::TCppScope_t scope)
300{
301// Find a callable matching the named operator (op) and the (left, right)
302// arguments in the global or these objects' namespaces.
303
304 bool reverse = false;
305 if (!CPPInstance_Check(left)) {
306 if (CPPInstance_Check(right))
307 reverse = true;
308 else
309 return nullptr;
310 }
311
312// retrieve the class names to match the signature of any found global functions
313 const std::string& lcname = ClassName(left);
314 const std::string& rcname = ClassName(right);
315 return FindBinaryOperator(lcname, rcname, op, scope, reverse);
316}
317
318//----------------------------------------------------------------------------
320 const std::string& lcname, const std::string& rcname,
321 const char* op, Cppyy::TCppScope_t scope, bool reverse)
322{
323// Find a global function with a matching signature; search __gnu_cxx, std::__1,
324// and __cppyy_internal pro-actively (as there's AFAICS no way to unearth 'using'
325// information).
326
327 if (rcname == "<unknown>" || lcname == "<unknown>")
328 return nullptr;
329
330 PyCallable* pyfunc = 0;
331
332 if (!scope) {
333 // TODO: the following should remain sync with what clingwrapper does in its
334 // type remapper; there must be a better way?
335 if (lcname == "str" || lcname == "unicode" || lcname == "complex")
336 scope = Cppyy::GetScope("std");
337 else scope = Cppyy::GetScope(TypeManip::extract_namespace(lcname));
338 }
339 if (scope)
340 pyfunc = BuildOperator(lcname, rcname, op, scope, reverse);
341
342 if (!pyfunc && scope != Cppyy::gGlobalScope) // search in global scope anyway
343 pyfunc = BuildOperator(lcname, rcname, op, Cppyy::gGlobalScope, reverse);
344
345 if (!pyfunc) {
346 // For GNU on clang, search the internal __gnu_cxx namespace for binary operators (is
347 // typically the case for STL iterators operator==/!=.
348 // TODO: only look in __gnu_cxx for iterators (and more generally: do lookups in the
349 // namespace where the class is defined
350 static Cppyy::TCppScope_t gnucxx = Cppyy::GetScope("__gnu_cxx");
351 if (gnucxx)
352 pyfunc = BuildOperator(lcname, rcname, op, gnucxx, reverse);
353 }
354
355 if (!pyfunc) {
356 // Same for clang (on Mac only?). TODO: find proper pre-processor magic to only use those
357 // specific namespaces that are actually around; although to be sure, this isn't expensive.
358 static Cppyy::TCppScope_t std__1 = Cppyy::GetScope("std::__1");
359
360 if (std__1
361#ifdef __APPLE__
362 && lcname.find("__wrap_iter") == std::string::npos // wrapper call does not compile
363#endif
364 ) {
365 pyfunc = BuildOperator(lcname, rcname, op, std__1, reverse);
366 }
367 }
368
369 if (!pyfunc) {
370 // One more, mostly for Mac, but again not sure whether this is not a general issue. Some
371 // operators are declared as friends only in classes, so then they're not found in the
372 // global namespace, so this helper let's the compiler resolve the operator.
373 static Cppyy::TCppScope_t s_intern = Cppyy::GetScope("__cppyy_internal");
374 if (s_intern) {
375 std::stringstream fname, proto;
376 if (strncmp(op, "==", 2) == 0) { fname << "is_equal<"; }
377 else if (strncmp(op, "!=", 2) == 0) { fname << "is_not_equal<"; }
378 else { fname << "not_implemented<"; }
379 fname << lcname << ", " << rcname << ">";
380 proto << "const " << lcname << "&, const " << rcname;
381 Cppyy::TCppMethod_t method = Cppyy::GetMethodTemplate(s_intern, fname.str(), proto.str());
382 if (method) pyfunc = new CPPFunction(s_intern, method);
383 }
384 }
385
386 return pyfunc;
387}
388
389//----------------------------------------------------------------------------
390static inline std::string AnnotationAsText(PyObject* pyobj)
391{
392 if (!CPyCppyy_PyText_Check(pyobj)) {
393 PyObject* pystr = PyObject_GetAttr(pyobj, CPyCppyy::PyStrings::gName);
394 if (!pystr) {
395 PyErr_Clear();
396 pystr = PyObject_Str(pyobj);
397 }
398
399 std::string str = CPyCppyy_PyText_AsString(pystr);
400 Py_DECREF(pystr);
401 return str;
402 }
403 return CPyCppyy_PyText_AsString(pyobj);
404}
405
406static bool AddTypeName(std::string& tmpl_name, PyObject* tn, PyObject* arg,
407 CPyCppyy::Utility::ArgPreference pref, int* pcnt = nullptr)
408{
409// Determine the appropriate C++ type for a given Python type; this is a helper because
410// it can recurse if the type is list or tuple and needs matching on std::vector.
411 using namespace CPyCppyy;
412 using namespace CPyCppyy::Utility;
413
414 if (tn == (PyObject*)&PyInt_Type) {
415 if (arg) {
416#if PY_VERSION_HEX < 0x03000000
417 long l = PyInt_AS_LONG(arg);
418 tmpl_name.append((l < INT_MIN || INT_MAX < l) ? "long" : "int");
419#else
420 PY_LONG_LONG ll = PyLong_AsLongLong(arg);
421 if (ll == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
422 PyErr_Clear();
423 PY_ULONG_LONG ull = PyLong_AsUnsignedLongLong(arg);
424 if (ull == (PY_ULONG_LONG)-1 && PyErr_Occurred()) {
425 PyErr_Clear();
426 tmpl_name.append("int"); // still out of range, will fail later
427 } else
428 tmpl_name.append("unsigned long long"); // since already failed long long
429 } else
430 tmpl_name.append((ll < INT_MIN || INT_MAX < ll) ? \
431 ((ll < LONG_MIN || LONG_MAX < ll) ? "long long" : "long") : "int");
432#endif
433 } else
434 tmpl_name.append("int");
435
436 return true;
437 }
438
439#if PY_VERSION_HEX < 0x03000000
440 if (tn == (PyObject*)&PyLong_Type) {
441 if (arg) {
442 PY_LONG_LONG ll = PyLong_AsLongLong(arg);
443 if (ll == (PY_LONG_LONG)-1 && PyErr_Occurred()) {
444 PyErr_Clear();
445 PY_ULONG_LONG ull = PyLong_AsUnsignedLongLong(arg);
446 if (ull == (PY_ULONG_LONG)-1 && PyErr_Occurred()) {
447 PyErr_Clear();
448 tmpl_name.append("long"); // still out of range, will fail later
449 } else
450 tmpl_name.append("unsigned long long"); // since already failed long long
451 } else
452 tmpl_name.append((ll < LONG_MIN || LONG_MAX < ll) ? "long long" : "long");
453 } else
454 tmpl_name.append("long");
455
456 return true;
457 }
458#endif
459
460 if (tn == (PyObject*)&PyFloat_Type) {
461 // special case for floats (Python-speak for double) if from argument (only)
462 tmpl_name.append(arg ? "double" : "float");
463 return true;
464 }
465
466#if PY_VERSION_HEX < 0x03000000
467 if (tn == (PyObject*)&PyString_Type) {
468#else
469 if (tn == (PyObject*)&PyUnicode_Type) {
470#endif
471 tmpl_name.append("std::string");
472 return true;
473 }
474
475 if (tn == (PyObject*)&PyList_Type || tn == (PyObject*)&PyTuple_Type) {
476 if (arg && PySequence_Size(arg)) {
477 std::string subtype{"std::initializer_list<"};
478 PyObject* item = PySequence_GetItem(arg, 0);
479 ArgPreference subpref = pref == kValue ? kValue : kPointer;
480 if (AddTypeName(subtype, (PyObject*)Py_TYPE(item), item, subpref)) {
481 tmpl_name.append(subtype);
482 tmpl_name.append(">");
483 }
484 Py_DECREF(item);
485 }
486
487 return true;
488 }
489
490 if (CPPScope_Check(tn)) {
491 tmpl_name.append(full_scope(Cppyy::GetScopedFinalName(((CPPClass*)tn)->fCppType)));
492 if (arg) {
493 // try to specialize the type match for the given object
494 CPPInstance* pyobj = (CPPInstance*)arg;
495 if (CPPInstance_Check(pyobj)) {
496 if (pyobj->fFlags & CPPInstance::kIsRValue)
497 tmpl_name.append("&&");
498 else {
499 if (pcnt) *pcnt += 1;
500 if ((pyobj->fFlags & CPPInstance::kIsReference) || pref == kPointer)
501 tmpl_name.push_back('*');
502 else if (pref != kValue)
503 tmpl_name.push_back('&');
504 }
505 }
506 }
507
508 return true;
509 }
510
511 if (tn == (PyObject*)&CPPOverload_Type) {
512 PyObject* tpName = arg ? \
513 PyObject_GetAttr(arg, PyStrings::gCppName) : \
514 CPyCppyy_PyText_FromString("void* (*)(...)");
515 tmpl_name.append(CPyCppyy_PyText_AsString(tpName));
516 Py_DECREF(tpName);
517
518 return true;
519 }
520
521 if (arg && PyCallable_Check(arg)) {
522 PyObject* annot = PyObject_GetAttr(arg, PyStrings::gAnnotations);
523 if (annot) {
524 if (PyDict_Check(annot) && 1 < PyDict_Size(annot)) {
525 PyObject* ret = PyDict_GetItemString(annot, "return");
526 if (ret) {
527 // dict is ordered, with the last value being the return type
528 std::ostringstream tpn;
529 tpn << (CPPScope_Check(ret) ? ClassName(ret) : AnnotationAsText(ret))
530 << " (*)(";
531
532 PyObject* values = PyDict_Values(annot);
533 for (Py_ssize_t i = 0; i < (PyList_GET_SIZE(values)-1); ++i) {
534 if (i) tpn << ", ";
535 PyObject* item = PyList_GET_ITEM(values, i);
536 tpn << (CPPScope_Check(item) ? full_scope(ClassName(item)) : AnnotationAsText(item));
537 }
538 Py_DECREF(values);
539
540 tpn << ')';
541 tmpl_name.append(tpn.str());
542
543 return true;
544
545 } else
546 PyErr_Clear();
547 }
548 Py_DECREF(annot);
549 } else
550 PyErr_Clear();
551
552 PyObject* tpName = PyObject_GetAttr(arg, PyStrings::gCppName);
553 if (tpName) {
554 const char* cname = CPyCppyy_PyText_AsString(tpName);
555 tmpl_name.append(CPPScope_Check(arg) ? full_scope(cname) : cname);
556 Py_DECREF(tpName);
557 return true;
558 }
559 PyErr_Clear();
560 }
561
562 for (auto nn : {PyStrings::gCppName, PyStrings::gName}) {
563 PyObject* tpName = PyObject_GetAttr(tn, nn);
564 if (tpName) {
565 tmpl_name.append(CPyCppyy_PyText_AsString(tpName));
566 Py_DECREF(tpName);
567 return true;
568 }
569 PyErr_Clear();
570 }
571
572 if (PyInt_Check(tn) || PyLong_Check(tn) || PyFloat_Check(tn)) {
573 // last ditch attempt, works for things like int values; since this is a
574 // source of errors otherwise, it is limited to specific types and not
575 // generally used (str(obj) can print anything ...)
576 PyObject* pystr = PyObject_Str(tn);
577 tmpl_name.append(CPyCppyy_PyText_AsString(pystr));
578 Py_DECREF(pystr);
579 return true;
580 }
581
582 return false;
583}
584
586 PyObject* pyname, PyObject* tpArgs, PyObject* args, ArgPreference pref, int argoff, int* pcnt)
587{
588// Helper to construct the "<type, type, ...>" part of a templated name (either
589// for a class or method lookup
590 bool justOne = !PyTuple_CheckExact(tpArgs);
591
592// Note: directly appending to string is a lot faster than stringstream
593 std::string tmpl_name;
594 tmpl_name.reserve(128);
595 if (pyname)
596 tmpl_name.append(CPyCppyy_PyText_AsString(pyname));
597 tmpl_name.push_back('<');
598
599 if (pcnt) *pcnt = 0; // count number of times 'pref' is used
600
601 Py_ssize_t nArgs = justOne ? 1 : PyTuple_GET_SIZE(tpArgs);
602 for (int i = argoff; i < nArgs; ++i) {
603 // add type as string to name
604 PyObject* tn = justOne ? tpArgs : PyTuple_GET_ITEM(tpArgs, i);
605 if (CPyCppyy_PyText_Check(tn)) {
606 tmpl_name.append(CPyCppyy_PyText_AsString(tn));
607 // some common numeric types (separated out for performance: checking for
608 // __cpp_name__ and/or __name__ is rather expensive)
609 } else {
610 if (!AddTypeName(tmpl_name, tn, (args ? PyTuple_GET_ITEM(args, i) : nullptr), pref, pcnt)) {
611 PyErr_SetString(PyExc_SyntaxError,
612 "could not construct C++ name from provided template argument.");
613 return "";
614 }
615 }
616
617 // add a comma, as needed (no space as internally, final names don't have them)
618 if (i != nArgs-1)
619 tmpl_name.push_back(',');
620 }
621
622// close template name
623 tmpl_name.push_back('>');
624
625 return tmpl_name;
626}
627
628//----------------------------------------------------------------------------
629static inline bool check_scope(const std::string& name)
630{
632}
633
634void CPyCppyy::Utility::ConstructCallbackPreamble(const std::string& retType,
635 const std::vector<std::string>& argtypes, std::ostringstream& code)
636{
637// Generate function setup to be used in callbacks (wrappers and overrides).
638 int nArgs = (int)argtypes.size();
639
640// return value and argument type converters
641 bool isVoid = retType == "void";
642 if (!isVoid)
643 code << " CPYCPPYY_STATIC std::unique_ptr<CPyCppyy::Converter, std::function<void(CPyCppyy::Converter*)>> "
644 "retconv{CPyCppyy::CreateConverter(\""
645 << retType << "\"), CPyCppyy::DestroyConverter};\n";
646 std::vector<bool> arg_is_ptr;
647 if (nArgs) {
648 arg_is_ptr.reserve(nArgs);
649 code << " CPYCPPYY_STATIC std::vector<std::unique_ptr<CPyCppyy::Converter, std::function<void(CPyCppyy::Converter*)>>> argcvs;\n"
650 << " if (argcvs.empty()) {\n"
651 << " argcvs.reserve(" << nArgs << ");\n";
652 for (int i = 0; i < nArgs; ++i) {
653 arg_is_ptr[i] = false;
654 code << " argcvs.emplace_back(CPyCppyy::CreateConverter(\"";
655 const std::string& at = argtypes[i];
656 const std::string& res_at = Cppyy::ResolveName(at);
657 const std::string& cpd = TypeManip::compound(res_at);
658 if (!cpd.empty() && check_scope(res_at)) {
659 // in case of a pointer, the original argument needs to be used to ensure
660 // the pointer-value remains comparable
661 //
662 // in case of a reference, there is no extra indirection on the C++ side as
663 // would be when converting a data member, so adjust the converter
664 arg_is_ptr[i] = cpd.back() == '*';
665 if (arg_is_ptr[i] || cpd.back() == '&') {
666 code << res_at.substr(0, res_at.size()-1);
667 } else code << at;
668 } else
669 code << at;
670 code << "\"), CPyCppyy::DestroyConverter);\n";
671 }
672 code << " }\n";
673 }
674
675// declare return value (TODO: this does not work for most non-builtin values)
676 if (!isVoid)
677 code << " " << retType << " ret{};\n";
678
679// acquire GIL
680 code << " PyGILState_STATE state = PyGILState_Ensure();\n";
681
682// build argument tuple if needed
683 if (nArgs) {
684 code << " std::vector<PyObject*> pyargs;\n";
685 code << " pyargs.reserve(" << nArgs << ");\n"
686 << " try {\n";
687 for (int i = 0; i < nArgs; ++i) {
688 code << " pyargs.emplace_back(argcvs[" << i << "]->FromMemory((void*)";
689 if (!arg_is_ptr[i]) code << '&';
690 code << "arg" << i << "));\n"
691 << " if (!pyargs.back()) throw " << i << ";\n";
692 }
693 code << " } catch(int) {\n"
694 << " for (auto pyarg : pyargs) Py_XDECREF(pyarg);\n"
695 << " CPyCppyy::PyException pyexc; PyGILState_Release(state); throw pyexc;\n"
696 << " }\n";
697 }
698}
699
700void CPyCppyy::Utility::ConstructCallbackReturn(const std::string& retType, int nArgs, std::ostringstream& code)
701{
702// Generate code for return value conversion and error handling.
703 bool isVoid = retType == "void";
704 bool isPtr = Cppyy::ResolveName(retType).back() == '*';
705
706 if (nArgs)
707 code << " for (auto pyarg : pyargs) Py_DECREF(pyarg);\n";
708 code << " bool cOk = (bool)pyresult;\n"
709 " if (pyresult) {\n";
710 if (isPtr) {
711 // If the return type is a CPPInstance, owned by Python, and the ref-count down
712 // to 1, the return will hold a dangling pointer, so set it to nullptr instead.
713 code << " if (!CPyCppyy::Instance_IsLively(pyresult))\n"
714 " ret = nullptr;\n"
715 " else {\n";
716 }
717 code << (isVoid ? "" : " cOk = retconv->ToMemory(pyresult, (void*)&ret);\n")
718 << " Py_DECREF(pyresult);\n }\n";
719 if (isPtr) code << " }\n";
720 code << " if (!cOk) {" // assume error set when converter failed
721// TODO: On Windows, throwing a C++ exception here makes the code hang; leave
722// the error be which allows at least one layer of propagation
723#ifdef _WIN32
724 " /* do nothing */ }\n"
725#else
726 " CPyCppyy::PyException pyexc; PyGILState_Release(state); throw pyexc; }\n"
727#endif
728 " PyGILState_Release(state);\n"
729 " return";
730 code << (isVoid ? ";\n }\n" : " ret;\n }\n");
731}
732
733
734//----------------------------------------------------------------------------
735static std::map<void*, PyObject*> sStdFuncLookup;
736static std::map<std::string, PyObject*> sStdFuncMakerLookup;
738 const std::string& retType, const std::string& signature, void* address)
739{
740// Convert a function pointer to an equivalent std::function<> object.
741 static int maker_count = 0;
742
743 auto pf = sStdFuncLookup.find(address);
744 if (pf != sStdFuncLookup.end()) {
745 Py_INCREF(pf->second);
746 return pf->second;
747 }
748
749 PyObject* maker = nullptr;
750
751 auto pm = sStdFuncMakerLookup.find(retType+signature);
752 if (pm == sStdFuncMakerLookup.end()) {
753 std::ostringstream fname;
754 fname << "ptr2func" << ++maker_count;
755
756 std::ostringstream code;
757 code << "namespace __cppyy_internal { std::function<"
758 << retType << signature << "> " << fname.str()
759 << "(intptr_t faddr) { return (" << retType << "(*)" << signature << ")faddr;} }";
760
761 if (!Cppyy::Compile(code.str())) {
762 PyErr_SetString(PyExc_TypeError, "conversion to std::function failed");
763 return nullptr;
764 }
765
766 PyObject* pyscope = CreateScopeProxy("__cppyy_internal");
767 maker = PyObject_GetAttrString(pyscope, fname.str().c_str());
768 Py_DECREF(pyscope);
769 if (!maker)
770 return nullptr;
771
772 // cache the new maker (TODO: does it make sense to use weakrefs?)
773 sStdFuncMakerLookup[retType+signature] = maker;
774 } else
775 maker = pm->second;
776
777 PyObject* args = PyTuple_New(1);
778 PyTuple_SET_ITEM(args, 0, PyLong_FromLongLong((intptr_t)address));
779 PyObject* func = PyObject_Call(maker, args, NULL);
780 Py_DECREF(args);
781
782 if (func) { // prevent moving this func object, since then it can not be reused
783 ((CPPInstance*)func)->fFlags |= CPPInstance::kIsLValue;
784 Py_INCREF(func); // TODO: use weak? The C++ maker doesn't go away either
785 sStdFuncLookup[address] = func;
786 }
787
788 return func;
789}
790
791
792//----------------------------------------------------------------------------
793bool CPyCppyy::Utility::InitProxy(PyObject* module, PyTypeObject* pytype, const char* name)
794{
795// Initialize a proxy class for use by python, and add it to the module.
796
797// finalize proxy type
798 if (PyType_Ready(pytype) < 0)
799 return false;
800
801// add proxy type to the given module
802 Py_INCREF(pytype); // PyModule_AddObject steals reference
803 if (PyModule_AddObject(module, (char*)name, (PyObject*)pytype) < 0) {
804 Py_DECREF(pytype);
805 return false;
806 }
807
808// declare success
809 return true;
810}
811
812//----------------------------------------------------------------------------
813Py_ssize_t CPyCppyy::Utility::GetBuffer(PyObject* pyobject, char tc, int size, void*& buf, bool check)
814{
815// Retrieve a linear buffer pointer from the given pyobject.
816
817// special case: don't handle character strings here (yes, they're buffers, but not quite)
818 if (PyBytes_Check(pyobject) || PyUnicode_Check(pyobject))
819 return 0;
820
821// special case: bytes array
822 if ((!check || tc == '*' || tc == 'B') && PyByteArray_CheckExact(pyobject)) {
823 buf = PyByteArray_AS_STRING(pyobject);
824 return PyByteArray_GET_SIZE(pyobject);
825 }
826
827// new-style buffer interface
828 if (PyObject_CheckBuffer(pyobject)) {
829 if (PySequence_Check(pyobject) && !PySequence_Size(pyobject))
830 return 0; // PyObject_GetBuffer() crashes on some platforms for some zero-sized seqeunces
831
832 Py_buffer bufinfo;
833 memset(&bufinfo, 0, sizeof(Py_buffer));
834 if (PyObject_GetBuffer(pyobject, &bufinfo, PyBUF_FORMAT) == 0) {
835 if (tc == '*' || strchr(bufinfo.format, tc)
836 // if `long int` and `int` are the same size (on Windows and 32bit Linux,
837 // for example), `ctypes` isn't too picky about the type format, so make
838 // sure both integer types pass the type check
839 || (sizeof(long int) == sizeof(int) && ((tc == 'I' && strchr(bufinfo.format, 'L')) ||
840 (tc == 'i' && strchr(bufinfo.format, 'l'))))
841 // complex float is 'Zf' in bufinfo.format, but 'z' in single char
842 || (tc == 'z' && strstr(bufinfo.format, "Zf"))
843 // allow 'signed char' ('b') from array to pass through '?' (bool as from struct)
844 || (tc == '?' && strchr(bufinfo.format, 'b'))
845 ) {
846 buf = bufinfo.buf;
847
848 if (check && bufinfo.itemsize != size) {
849 PyErr_Format(PyExc_TypeError,
850 "buffer itemsize (%ld) does not match expected size (%d)", bufinfo.itemsize, size);
851 CPyCppyy_PyBuffer_Release(pyobject, &bufinfo);
852 return 0;
853 }
854
855 Py_ssize_t buflen = 0;
856 if (buf && bufinfo.ndim == 0)
857 buflen = bufinfo.len/bufinfo.itemsize;
858 else if (buf && bufinfo.ndim == 1)
859 buflen = bufinfo.shape ? bufinfo.shape[0] : bufinfo.len/bufinfo.itemsize;
860 CPyCppyy_PyBuffer_Release(pyobject, &bufinfo);
861 if (buflen)
862 return buflen;
863 } else {
864 // have buf, but format mismatch: bail out now, otherwise the old
865 // code will return based on itemsize match
866 CPyCppyy_PyBuffer_Release(pyobject, &bufinfo);
867 return 0;
868 }
869 } else if (bufinfo.obj)
870 CPyCppyy_PyBuffer_Release(pyobject, &bufinfo);
871 PyErr_Clear();
872 }
873
874// attempt to retrieve pointer through old-style buffer interface
875 PyBufferProcs* bufprocs = Py_TYPE(pyobject)->tp_as_buffer;
876
877 PySequenceMethods* seqmeths = Py_TYPE(pyobject)->tp_as_sequence;
878 if (seqmeths != 0 && bufprocs != 0
879#if PY_VERSION_HEX < 0x03000000
880 && bufprocs->bf_getwritebuffer != 0
881 && (*(bufprocs->bf_getsegcount))(pyobject, 0) == 1
882#else
883 && bufprocs->bf_getbuffer != 0
884#endif
885 ) {
886
887 // get the buffer
888#if PY_VERSION_HEX < 0x03000000
889 Py_ssize_t buflen = (*(bufprocs->bf_getwritebuffer))(pyobject, 0, &buf);
890#else
891 Py_buffer bufinfo;
892 (*(bufprocs->bf_getbuffer))(pyobject, &bufinfo, PyBUF_WRITABLE);
893 buf = (char*)bufinfo.buf;
894 Py_ssize_t buflen = bufinfo.len;
895 CPyCppyy_PyBuffer_Release(pyobject, &bufinfo);
896#endif
897
898 if (buf && check == true) {
899 // determine buffer compatibility (use "buf" as a status flag)
900 PyObject* pytc = tc != '*' ? PyObject_GetAttr(pyobject, PyStrings::gTypeCode) : nullptr;
901 if (pytc != 0) { // for array objects
902 char cpytc = CPyCppyy_PyText_AsString(pytc)[0];
903 if (!(cpytc == tc || (tc == '?' && cpytc == 'b')))
904 buf = 0; // no match
905 Py_DECREF(pytc);
906 } else if (seqmeths->sq_length &&
907 (int)(buflen/(*(seqmeths->sq_length))(pyobject)) == size) {
908 // this is a gamble ... may or may not be ok, but that's for the user
909 PyErr_Clear();
910 } else if (buflen == size) {
911 // also a gamble, but at least 1 item will fit into the buffer, so very likely ok ...
912 PyErr_Clear();
913 } else {
914 buf = 0; // not compatible
915
916 // clarify error message
917 PyObject* pytype = 0, *pyvalue = 0, *pytrace = 0;
918 PyErr_Fetch(&pytype, &pyvalue, &pytrace);
920 (char*)"%s and given element size (%ld) do not match needed (%d)",
922 seqmeths->sq_length ? (long)(buflen/(*(seqmeths->sq_length))(pyobject)) : (long)buflen,
923 size);
924 Py_DECREF(pyvalue);
925 PyErr_Restore(pytype, pyvalue2, pytrace);
926 }
927 }
928
929 if (!buf) return 0;
930 return buflen/(size ? size : 1);
931 }
932
933 return 0;
934}
935
936//----------------------------------------------------------------------------
937std::string CPyCppyy::Utility::MapOperatorName(const std::string& name, bool bTakesParams, bool* stubbed)
938{
939// Map the given C++ operator name on the python equivalent.
940 if (8 < name.size() && name.substr(0, 8) == "operator") {
941 std::string op = name.substr(8, std::string::npos);
942
943 // stripping ...
944 std::string::size_type start = 0, end = op.size();
945 while (start < end && isspace(op[start])) ++start;
946 while (start < end && isspace(op[end-1])) --end;
947 op = op.substr(start, end - start);
948
949 // certain operators should be removed completely (e.g. operator delete & friends)
950 if (gOpRemove.find(op) != gOpRemove.end())
951 return "";
952
953 // check first if none, to prevent spurious deserializing downstream
954 TC2POperatorMapping_t::iterator pop = gC2POperatorMapping.find(op);
955 if (pop == gC2POperatorMapping.end() && gOpSkip.find(op) == gOpSkip.end()) {
956 op = Cppyy::ResolveName(op);
957 pop = gC2POperatorMapping.find(op);
958 }
959
960 // map C++ operator to python equivalent, or made up name if no equivalent exists
961 if (pop != gC2POperatorMapping.end()) {
962 return pop->second;
963
964 } else if (op == "*") {
965 // dereference v.s. multiplication of two instances
966 if (!bTakesParams) return "__deref__";
967 if (stubbed) *stubbed = true;
968 return "__mul__";
969
970 } else if (op == "/") {
971 // no unary, but is stubbed
972 return CPPYY__div__;
973
974 } else if (op == "+") {
975 // unary positive v.s. addition of two instances
976 if (!bTakesParams) return "__pos__";
977 if (stubbed) *stubbed = true;
978 return "__add__";
979
980 } else if (op == "-") {
981 // unary negative v.s. subtraction of two instances
982 if (!bTakesParams) return "__neg__";
983 if (stubbed) *stubbed = true;
984 return "__sub__";
985
986 } else if (op == "++") {
987 // prefix v.s. postfix increment
988 return bTakesParams ? "__postinc__" : "__preinc__";
989
990 } else if (op == "--") {
991 // prefix v.s. postfix decrement
992 return bTakesParams ? "__postdec__" : "__predec__";
993 }
994
995 }
996
997// might get here, as not all operator methods are handled (new, delete, etc.)
998 return name;
999}
1000
1001//----------------------------------------------------------------------------
1003{
1004// Retrieve the class name from the given Python instance.
1005 std::string clname = "<unknown>";
1006 PyObject* pyclass = (PyObject*)Py_TYPE(pyobj);
1007 PyObject* pyname = PyObject_GetAttr(pyclass, PyStrings::gCppName);
1008 if (!pyname) {
1009 PyErr_Clear();
1010 pyname = PyObject_GetAttr(pyclass, PyStrings::gName);
1011 }
1012
1013 if (pyname) {
1014 clname = CPyCppyy_PyText_AsString(pyname);
1015 Py_DECREF(pyname);
1016 } else
1017 PyErr_Clear();
1018 return clname;
1019}
1020
1021//----------------------------------------------------------------------------
1022static std::set<std::string> sIteratorTypes;
1023bool CPyCppyy::Utility::IsSTLIterator(const std::string& classname)
1024{
1025// attempt to recognize STL iterators (TODO: probably belongs in the backend), using
1026// a couple of common container classes with different iterator protocols (note that
1027// mapping iterators are handled separately in the pythonizations) as exemplars (the
1028// actual, resolved, names will be compiler-specific) that are picked b/c they are
1029// baked into the CoreLegacy dictionary
1030 if (sIteratorTypes.empty()) {
1031 std::string tt = "<int>::";
1032 for (auto c : {"std::vector", "std::list", "std::deque"}) {
1033 for (auto i : {"iterator", "const_iterator"}) {
1034 const std::string& itname = Cppyy::ResolveName(c+tt+i);
1035 auto pos = itname.find('<');
1036 if (pos != std::string::npos)
1037 sIteratorTypes.insert(itname.substr(0, pos));
1038 }
1039 }
1040 }
1041
1042 auto pos = classname.find('<');
1043 if (pos != std::string::npos)
1044 return sIteratorTypes.find(classname.substr(0, pos)) != sIteratorTypes.end();
1045 return false;
1046}
1047
1048
1049//----------------------------------------------------------------------------
1051{
1052 Py_XDECREF(fEq);
1053 Py_XDECREF(fNe);
1054 Py_XDECREF(fLAdd); Py_XDECREF(fRAdd);
1055 Py_XDECREF(fSub);
1056 Py_XDECREF(fLMul); Py_XDECREF(fRMul);
1057 Py_XDECREF(fDiv);
1058 Py_XDECREF(fHash);
1059}
1060
1061
1062//----------------------------------------------------------------------------
1064{
1065// Re-acquire the GIL before calling PyErr_Occurred() in case it has been
1066// released; note that the p2.2 code assumes that there are no callbacks in
1067// C++ to python (or at least none returning errors).
1068#if PY_VERSION_HEX >= 0x02030000
1069 PyGILState_STATE gstate = PyGILState_Ensure();
1070 PyObject* e = PyErr_Occurred();
1071 PyGILState_Release(gstate);
1072#else
1073 if (PyThreadState_GET())
1074 return PyErr_Occurred();
1075 PyObject* e = 0;
1076#endif
1077
1078 return e;
1079}
1080
1081
1082//----------------------------------------------------------------------------
1083size_t CPyCppyy::Utility::FetchError(std::vector<PyError_t>& errors, bool is_cpp)
1084{
1085// Fetch the current python error, if any, and store it for future use.
1086 if (PyErr_Occurred()) {
1087 PyError_t e{is_cpp};
1088 PyErr_Fetch(&e.fType, &e.fValue, &e.fTrace);
1089 errors.push_back(e);
1090 }
1091 return errors.size();
1092}
1093
1094//----------------------------------------------------------------------------
1095void CPyCppyy::Utility::SetDetailedException(std::vector<PyError_t>& errors, PyObject* topmsg, PyObject* defexc)
1096{
1097// Use the collected exceptions to build up a detailed error log.
1098 if (errors.empty()) {
1099 // should not happen ...
1100 PyErr_SetString(defexc, CPyCppyy_PyText_AsString(topmsg));
1101 Py_DECREF(topmsg);
1102 return;
1103 }
1104
1105// if a _single_ exception was thrown from C++, assume it has priority (see below)
1106 PyError_t* unique_from_cpp = nullptr;
1107 for (auto& e : errors) {
1108 if (e.fIsCpp) {
1109 if (!unique_from_cpp)
1110 unique_from_cpp = &e;
1111 else {
1112 // two C++ exceptions, resort to default behavior
1113 unique_from_cpp = nullptr;
1114 break;
1115 }
1116 }
1117 }
1118
1119 if (unique_from_cpp) {
1120 // report only this error; the idea here is that all other errors come from
1121 // the bindings (e.g. argument conversion errors), while the exception from
1122 // C++ means that it originated from an otherwise successful call
1123
1124 // bind the original C++ object, rather than constructing from topmsg, as it
1125 // is expected to have informative state
1126 Py_INCREF(unique_from_cpp->fType); Py_INCREF(unique_from_cpp->fValue); Py_XINCREF(unique_from_cpp->fTrace);
1127 PyErr_Restore(unique_from_cpp->fType, unique_from_cpp->fValue, unique_from_cpp->fTrace);
1128 } else {
1129 // try to consolidate Python exceptions, otherwise select default
1130 PyObject* exc_type = nullptr;
1131 for (auto& e : errors) {
1132 if (!exc_type) exc_type = e.fType;
1133 else if (exc_type != e.fType) {
1134 exc_type = defexc;
1135 break;
1136 }
1137 }
1138
1139 // add the details to the topmsg
1140 PyObject* separator = CPyCppyy_PyText_FromString("\n ");
1141 for (auto& e : errors) {
1142 CPyCppyy_PyText_Append(&topmsg, separator);
1143 if (CPyCppyy_PyText_Check(e.fValue)) {
1144 CPyCppyy_PyText_Append(&topmsg, e.fValue);
1145 } else if (e.fValue) {
1146 PyObject* excstr = PyObject_Str(e.fValue);
1147 if (!excstr) {
1148 PyErr_Clear();
1149 excstr = PyObject_Str((PyObject*)Py_TYPE(e.fValue));
1150 }
1151 CPyCppyy_PyText_AppendAndDel(&topmsg, excstr);
1152 } else {
1154 CPyCppyy_PyText_FromString("unknown exception"));
1155 }
1156 }
1157
1158 Py_DECREF(separator);
1159
1160 // set the python exception
1161 PyErr_SetString(exc_type, CPyCppyy_PyText_AsString(topmsg));
1162 }
1163
1164// cleanup stored errors and done with topmsg (whether used or not)
1165 std::for_each(errors.begin(), errors.end(), PyError_t::Clear);
1166 Py_DECREF(topmsg);
1167}
1168
1169
1170//----------------------------------------------------------------------------
1171static bool includesDone = false;
1173{
1174// setup Python API for callbacks
1175 if (!includesDone) {
1176 bool okay = Cppyy::Compile(
1177 // basic API (converters etc.)
1178 "#include \"CPyCppyy/API.h\"\n"
1179
1180 // utilities from the CPyCppyy public API
1181 "#include \"CPyCppyy/DispatchPtr.h\"\n"
1182 "#include \"CPyCppyy/PyException.h\"\n"
1183 );
1184 includesDone = okay;
1185 }
1186
1187 return includesDone;
1188}
#define Py_TYPE(ob)
Definition CPyCppyy.h:196
#define CPPYY__long__
Definition CPyCppyy.h:109
#define CPPYY__div__
Definition CPyCppyy.h:111
PyDictEntry *(* dict_lookup_func)(PyDictObject *, PyObject *, long)
Definition CPyCppyy.h:44
#define CPyCppyy_PyText_InternFromString
Definition CPyCppyy.h:82
int Py_ssize_t
Definition CPyCppyy.h:215
#define PyBytes_Check
Definition CPyCppyy.h:61
#define CPyCppyy_PyText_Append
Definition CPyCppyy.h:83
#define CPyCppyy_PyText_AsString
Definition CPyCppyy.h:76
#define CPyCppyy_PyText_AppendAndDel
Definition CPyCppyy.h:84
void CPyCppyy_PyBuffer_Release(PyObject *, Py_buffer *view)
Definition CPyCppyy.h:282
#define CPyCppyy_PyText_FromFormat
Definition CPyCppyy.h:80
#define CPyCppyy_PyText_FromString
Definition CPyCppyy.h:81
#define CPPYY__idiv__
Definition CPyCppyy.h:110
#define CPyCppyy_PyText_Check
Definition CPyCppyy.h:74
unsigned long long PY_ULONG_LONG
Definition Cppyy.h:31
long long PY_LONG_LONG
Definition Cppyy.h:23
_object PyObject
#define c(i)
Definition RSha256.hxx:101
#define e(i)
Definition RSha256.hxx:103
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
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 cname
char name[80]
Definition TGX11.cxx:110
static std::set< std::string > sIteratorTypes
Definition Utility.cxx:1022
static bool includesDone
Definition Utility.cxx:1171
static TC2POperatorMapping_t gC2POperatorMapping
Definition Utility.cxx:32
static CPyCppyy::PyCallable * BuildOperator(const std::string &lcname, const std::string &rcname, const char *op, Cppyy::TCppScope_t scope, bool reverse=false)
Definition Utility.cxx:265
static std::set< std::string > gOpRemove
Definition Utility.cxx:34
static std::map< std::string, PyObject * > sStdFuncMakerLookup
Definition Utility.cxx:736
static std::set< std::string > gOpSkip
Definition Utility.cxx:33
static std::map< void *, PyObject * > sStdFuncLookup
Definition Utility.cxx:735
static bool AddTypeName(std::string &tmpl_name, PyObject *tn, PyObject *arg, CPyCppyy::Utility::ArgPreference pref, int *pcnt=nullptr)
Definition Utility.cxx:406
static bool check_scope(const std::string &name)
Definition Utility.cxx:629
std::map< std::string, std::string > TC2POperatorMapping_t
Definition Utility.cxx:31
static std::string AnnotationAsText(PyObject *pyobj)
Definition Utility.cxx:390
const char * proto
Definition civetweb.c:17535
void AdoptMethod(PyCallable *pc)
Cppyy::TCppType_t fCppType
Definition CPPScope.h:55
std::string clean_type(const std::string &cppname, bool template_strip=true, bool const_strip=true)
PyCallable * FindBinaryOperator(PyObject *left, PyObject *right, const char *op, Cppyy::TCppScope_t scope=0)
Definition Utility.cxx:298
void ConstructCallbackPreamble(const std::string &retType, const std::vector< std::string > &argtypes, std::ostringstream &code)
Definition Utility.cxx:634
void ConstructCallbackReturn(const std::string &retType, int nArgs, std::ostringstream &code)
Definition Utility.cxx:700
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
PyObject * FuncPtr2StdFunction(const std::string &retType, const std::string &signature, void *address)
Definition Utility.cxx:737
PyCallable * FindUnaryOperator(PyObject *pyclass, const char *op)
Definition Utility.cxx:283
size_t FetchError(std::vector< PyError_t > &, bool is_cpp=false)
Definition Utility.cxx:1083
std::string MapOperatorName(const std::string &name, bool bTakesParames, bool *stubbed=nullptr)
Definition Utility.cxx:937
void SetDetailedException(std::vector< PyError_t > &errors, PyObject *topmsg, PyObject *defexc)
Definition Utility.cxx:1095
bool InitProxy(PyObject *module, PyTypeObject *pytype, const char *name)
Definition Utility.cxx:793
bool AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Definition Utility.cxx:186
bool IsSTLIterator(const std::string &classname)
Definition Utility.cxx:1023
std::string ClassName(PyObject *pyobj)
Definition Utility.cxx:1002
PyObject * PyErr_Occurred_WithGIL()
Definition Utility.cxx:1063
CPPOverload * CPPOverload_New(const std::string &name, std::vector< PyCallable * > &methods)
unsigned long PyLongOrInt_AsULong(PyObject *pyobject)
Definition Utility.cxx:133
PyObject * gDefaultObject
PyObject * CustomInstanceMethod_New(PyObject *func, PyObject *self, PyObject *pyclass)
bool gDictLookupActive
Definition Utility.cxx:28
dict_lookup_func gDictLookupOrg
Definition Utility.cxx:27
PyObject * CreateScopeProxy(Cppyy::TCppScope_t, const unsigned flags=0)
bool CPPOverload_Check(T *object)
Definition CPPOverload.h:90
bool CPPScope_Check(T *object)
Definition CPPScope.h:81
PY_ULONG_LONG PyLongOrInt_AsULong64(PyObject *pyobject)
Definition Utility.cxx:160
bool CPPInstance_Check(T *object)
PyObject * gNullPtrObject
size_t TCppIndex_t
Definition cpp_cppyy.h:24
intptr_t TCppMethod_t
Definition cpp_cppyy.h:22
RPY_EXPORTED bool Compile(const std::string &code, bool silent=false)
RPY_EXPORTED TCppScope_t gGlobalScope
Definition cpp_cppyy.h:53
RPY_EXPORTED TCppMethod_t GetMethodTemplate(TCppScope_t scope, const std::string &name, const std::string &proto)
RPY_EXPORTED std::string ResolveName(const std::string &cppitem_name)
RPY_EXPORTED std::string GetScopedFinalName(TCppType_t type)
RPY_EXPORTED TCppMethod_t GetMethod(TCppScope_t scope, TCppIndex_t imeth)
RPY_EXPORTED TCppScope_t GetScope(const std::string &scope_name)
size_t TCppScope_t
Definition cpp_cppyy.h:18
RPY_EXPORTED TCppIndex_t GetGlobalOperator(TCppType_t scope, const std::string &lc, const std::string &rc, const std::string &op)
static void Clear(PyError_t &e)
Definition Utility.h:90
TLine l
Definition textangle.C:4
auto * tt
Definition textangle.C:16