54 struct InitOperatorMapping_t {
56 InitOperatorMapping_t() {
116#if PY_VERSION_HEX < 0x03000000
122 } initOperatorMapping_;
124 std::once_flag sOperatorTemplateFlag;
125 void InitOperatorTemplate() {
127 "namespace _pyroot_internal { template<class C1, class C2>"
128 " bool is_equal(const C1& c1, const C2& c2){ return (bool)(c1 == c2); } }" );
130 "namespace _pyroot_internal { template<class C1, class C2>"
131 " bool is_not_equal(const C1& c1, const C2& c2){ return (bool)(c1 != c2); } }" );
134 inline void RemoveConst( std::string& cleanName ) {
135 std::string::size_type spos = std::string::npos;
136 while ( ( spos = cleanName.find(
"const" ) ) != std::string::npos ) {
137 cleanName.swap( cleanName.erase( spos, 5 ) );
148 ULong_t ul = PyLong_AsUnsignedLong( pyobject );
149 if ( PyErr_Occurred() && PyInt_Check( pyobject ) ) {
151 Long_t i = PyInt_AS_LONG( pyobject );
155 PyErr_SetString( PyExc_ValueError,
156 "can\'t convert negative value to unsigned long" );
168 ULong64_t ull = PyLong_AsUnsignedLongLong( pyobject );
169 if ( PyErr_Occurred() && PyInt_Check( pyobject ) ) {
171 Long_t i = PyInt_AS_LONG( pyobject );
175 PyErr_SetString( PyExc_ValueError,
176 "can\'t convert negative value to unsigned long long" );
187 PyObject* pyclass,
const char* label, PyCFunction cfunc,
int flags )
190 static std::list< PyMethodDef > s_pymeths;
192 s_pymeths.push_back( PyMethodDef() );
193 PyMethodDef* pdef = &s_pymeths.back();
194 pdef->ml_name =
const_cast< char*
>( label );
195 pdef->ml_meth = cfunc;
196 pdef->ml_flags = flags;
199 PyObject* func = PyCFunction_New( pdef, NULL );
201 Bool_t isOk = PyObject_SetAttrString( pyclass, pdef->ml_name, method ) == 0;
205 if ( PyErr_Occurred() )
209 PyErr_Format( PyExc_TypeError,
"could not add method %s", label );
221 PyObject* pyfunc = PyObject_GetAttrString( pyclass,
const_cast< char*
>( func ) );
225 Bool_t isOk = PyObject_SetAttrString( pyclass,
const_cast< char*
>( label ), pyfunc ) == 0;
237 (
MethodProxy*)PyObject_GetAttrString( pyclass,
const_cast< char*
>( label ) );
241 if ( PyErr_Occurred() )
245 Bool_t isOk = PyObject_SetAttrString(
246 pyclass,
const_cast< char*
>( label ), (
PyObject*)method ) == 0;
264 (
MethodProxy*)PyObject_GetAttrString( pyclass,
const_cast< char*
>( method ) );
266 Py_XDECREF( derivedMethod );
271 if ( ! mro || ! PyTuple_Check( mro ) ) {
273 Py_DECREF( derivedMethod );
278 for (
int i = 1; i < PyTuple_GET_SIZE( mro ); ++i ) {
280 PyTuple_GET_ITEM( mro, i ),
const_cast< char*
>( method ) );
282 if ( ! baseMethod ) {
290 Py_DECREF( baseMethod );
297 Py_XDECREF( baseMethod );
298 Py_DECREF( derivedMethod );
304 Py_DECREF( baseMethod );
305 Py_DECREF( derivedMethod );
316 PyObject* left,
PyObject* right,
const char* op,
const char* label,
const char* alt,
bool lazy )
329 Py_DECREF( pyclass );
337 PyObject* pyclass,
const char* op,
const char* label,
const char* alt,
bool lazy )
351 const char* op,
TClass* klass = 0 ) {
352 std::string opname =
"operator";
354 std::string
proto = lcname +
", " + rcname;
365 const std::string& rcname,
const char* op,
const char* label,
const char* alt,
bool lazy )
375 if ( !lazy && !
gApplication && (strcmp( op,
"==" ) == 0 || strcmp( op,
"!=" ) == 0) )
381 static bool gnucxx_exists = (bool)gnucxx.
GetClass();
386 static bool std__1_exists = (bool)std__1.
GetClass();
391 std::call_once( sOperatorTemplateFlag, InitOperatorTemplate );
392 static TClassRef _pr_int(
"_pyroot_internal" );
395 if ( gnucxx_exists ) {
400 if ( ! pyfunc && std__1_exists ) {
406 std::string::size_type pos = lcname.substr(0, lcname.find(
'<')).rfind(
"::" );
407 if ( pos != std::string::npos ) {
421 if ( ! pyfunc && _pr_int.
GetClass() &&
422 lcname.find(
"iterator" ) != std::string::npos &&
423 rcname.find(
"iterator" ) != std::string::npos ) {
427 std::stringstream fname;
428 if ( strncmp( op,
"==", 2 ) == 0 ) { fname <<
"is_equal<"; }
429 else if ( strncmp( op,
"!=", 2 ) == 0 ) { fname <<
"is_not_equal<"; }
430 else { fname <<
"not_implemented<"; }
431 fname << lcname <<
", " << rcname <<
">";
438 if ( lc && strcmp(op,
"==") != 0 && strcmp(op,
"!=") != 0 ) {
439 std::string opname =
"operator"; opname += op;
472 Py_ssize_t nArgs = PyTuple_GET_SIZE( tpArgs );
473 for (
int i = argoff; i < nArgs; ++i ) {
475 PyObject* tn = PyTuple_GET_ITEM( tpArgs, i );
489 auto arg = PyTuple_GET_ITEM(args, i);
492 if (pcnt) *pcnt += 1;
495 }
else if (pref !=
kValue) {
503 if ( strcmp( tpNameStr,
"str" ) == 0 ) {
508 else if (inferredTypes && strcmp(tpNameStr,
"float") == 0) {
513 }
else if ( PyInt_Check( tn ) || PyLong_Check( tn ) || PyFloat_Check( tn ) ) {
517 PyObject* pystr = PyObject_Str( tn );
521 PyErr_SetString( PyExc_SyntaxError,
"could not get __cppname__ from provided template argument. Is it a str, class, type or int?" );
526 if ( i != nArgs - 1 )
545 if ( PyType_Ready( pytype ) < 0 )
550 if ( PyModule_AddObject( module, (
char*)
name, (
PyObject*)pytype ) < 0 ) {
569 PyBufferProcs* bufprocs =
Py_TYPE(pyobject)->tp_as_buffer;
571 PySequenceMethods* seqmeths =
Py_TYPE(pyobject)->tp_as_sequence;
572 if ( seqmeths != 0 && bufprocs != 0
573#
if PY_VERSION_HEX < 0x03000000
574 && bufprocs->bf_getwritebuffer != 0
575 && (*(bufprocs->bf_getsegcount))( pyobject, 0 ) == 1
577 && bufprocs->bf_getbuffer != 0
582#if PY_VERSION_HEX < 0x03000000
583 Py_ssize_t buflen = (*(bufprocs->bf_getwritebuffer))( pyobject, 0, &buf );
586 (*(bufprocs->bf_getbuffer))( pyobject, &bufinfo, PyBUF_WRITABLE );
587 buf = (
char*)bufinfo.buf;
589#
if PY_VERSION_HEX < 0x03010000
590 PyBuffer_Release( pyobject, &bufinfo );
592 PyBuffer_Release( &bufinfo );
596 if ( buf && check ==
kTRUE ) {
603 }
else if ( seqmeths->sq_length &&
604 (
int)(buflen / (*(seqmeths->sq_length))( pyobject )) == size ) {
607 }
else if ( buflen == size ) {
614 PyObject* pytype = 0, *pyvalue = 0, *pytrace = 0;
615 PyErr_Fetch( &pytype, &pyvalue, &pytrace );
617 (
char*)
"%s and given element size (%ld) do not match needed (%d)",
619 seqmeths->sq_length ? (
Long_t)(buflen / (*(seqmeths->sq_length))( pyobject )) : (
Long_t)buflen,
621 Py_DECREF( pyvalue );
622 PyErr_Restore( pytype, pyvalue2, pytrace );
637 if ( 8 <
name.size() &&
name.substr( 0, 8 ) ==
"operator" ) {
638 std::string op =
name.substr( 8, std::string::npos );
641 std::string::size_type start = 0, end = op.size();
642 while ( start < end && isspace( op[ start ] ) ) ++start;
643 while ( start < end && isspace( op[ end-1 ] ) ) --end;
651 }
else if ( op ==
"*" ) {
653 return bTakesParams ?
"__mul__" :
"__deref__";
655 }
else if ( op ==
"+" ) {
657 return bTakesParams ?
"__add__" :
"__pos__";
659 }
else if ( op ==
"-" ) {
661 return bTakesParams ?
"__sub__" :
"__neg__";
663 }
else if ( op ==
"++" ) {
665 return bTakesParams ?
"__postinc__" :
"__preinc__";
667 }
else if ( op ==
"--" ) {
669 return bTakesParams ?
"__postdec__" :
"__predec__";
683 std::string cleanName =
name;
684 RemoveConst( cleanName );
687 for (
int ipos = (
int)cleanName.size()-1; 0 <= ipos; --ipos ) {
688 char c = cleanName[ipos];
689 if ( isspace(
c ) )
continue;
690 if ( isalnum(
c ) ||
c ==
'_' ||
c ==
'>' )
break;
707 std::string cleanName =
name;
708 RemoveConst( cleanName );
710 if ( cleanName[cleanName.size()-1] ==
']' ) {
711 std::string::size_type idx = cleanName.rfind(
'[' );
712 if ( idx != std::string::npos ) {
713 const std::string asize = cleanName.substr( idx+1, cleanName.size()-2 );
714 return strtoul( asize.c_str(), NULL, 0 );
727 std::string clname =
"<unknown>";
729 if ( pyclass != 0 ) {
745 Py_DECREF( pyclass );
846 static const char* emptyString =
"";
847 if (!location) location = emptyString;
855 PyErr_WarnExplicit( NULL, (
char*)msg, (
char*)location, 0, (
char*)
"ROOT", NULL );
871 const char* retType,
const std::vector<std::string>& signature,
const char* callback )
875 if ( ! PyCallable_Check( pyfunc ) )
884 std::ostringstream funcName;
885 funcName <<
"pyrootGenFun" << fid;
888 std::ostringstream sigDecl, argsig;
889 std::vector<std::string>::size_type nargs = signature.size();
890 for ( std::vector<std::string>::size_type i = 0; i < nargs; ++i ) {
891 sigDecl << signature[i] <<
" a" << i;
892 argsig <<
", a" << i;
893 if ( i != nargs-1 ) sigDecl <<
", ";
897 std::ostringstream declCode;
898 declCode <<
"namespace PyROOT { "
899 << retType <<
" " << callback <<
"(void*, Long_t, " << sigDecl.str() <<
"); }\n"
900 << retType <<
" " << funcName.str() <<
"(" << sigDecl.str()
901 <<
") { void* v0 = (void*)" << (
void*)pyfunc <<
"; "
902 <<
"return PyROOT::" << callback <<
"(v0, " << user << argsig.str() <<
"); }";
908 std::ostringstream fptrCode;
909 fptrCode <<
"void* pyrootPtrVar" << fid <<
" = (void*)" << funcName.str()
910 <<
"; pyrootPtrVar" << fid <<
";";
913 void* fptr = (
void*)
gInterpreter->ProcessLineSynch( fptrCode.str().c_str() );
915 PyErr_SetString( PyExc_SyntaxError,
"could not generate C++ callback wrapper" );
927#if PY_VERSION_HEX >= 0x02030000
928 PyGILState_STATE gstate = PyGILState_Ensure();
930 PyGILState_Release( gstate );
932 if ( PyThreadState_GET() )
933 return PyErr_Occurred();
943 static int (*sOldInputHook)() = NULL;
944 static PyThreadState* sInputHookEventThreadState = NULL;
946 static int EventInputHook()
950 PyEval_RestoreThread( sInputHookEventThreadState );
954 if ( sOldInputHook )
return sOldInputHook();
963 if ( PyOS_InputHook && PyOS_InputHook != &EventInputHook )
964 sOldInputHook = PyOS_InputHook;
966 sInputHookEventThreadState = PyThreadState_Get();
968 PyOS_InputHook = (int (*)())&EventInputHook;
969 Py_INCREF( Py_None );
976 PyOS_InputHook = sOldInputHook;
977 sInputHookEventThreadState = NULL;
979 Py_INCREF( Py_None );
#define PyROOT_PyUnicode_Append
#define PyROOT_PyUnicode_Check
#define PyROOT_PyUnicode_AsString
#define PyROOT_PyUnicode_AppendAndDel
PyDictEntry *(* dict_lookup_func)(PyDictObject *, PyObject *, Long_t)
#define PyROOT_PyUnicode_FromString
#define PyROOT_PyUnicode_FromFormat
#define PyROOT_PyUnicode_GetSize
unsigned long long ULong64_t
R__EXTERN TApplication * gApplication
void DefaultErrorHandler(int level, Bool_t abort, const char *location, const char *msg)
The default error handler function.
R__EXTERN Int_t gErrorIgnoreLevel
R__EXTERN TSystem * gSystem
R__EXTERN TVirtualMutex * gGlobalMutex
static Cppyy::TCppMethod_t FindAndAddOperator(const std::string &lcname, const std::string &rcname, const char *op, TClass *klass=0)
Helper to find a function with matching signature in 'funcs'.
static TC2POperatorMapping_t gC2POperatorMapping
std::map< std::string, std::string > TC2POperatorMapping_t
void AddMethod(PyCallable *pc)
Fill in the data of a freshly created method proxy.
TClassRef is used to implement a permanent reference to a TClass object.
TClass * GetClass() const
TClass instances represent classes, structs and namespaces in the ROOT type system.
TMethod * GetMethodWithPrototype(const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
Find the method with a given prototype.
ClassInfo_t * GetClassInfo() const
TMethod * GetMethodAny(const char *method)
Return pointer to method without looking at parameters.
TFunctionTemplate * GetFunctionTemplate(const char *name)
static TClass * GetClass(const char *name, Bool_t load=kTRUE, Bool_t silent=kFALSE)
Static method returning pointer to TClass of the specified class name.
Dictionary for function template This class describes one single function template.
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
std::string ResolveName(const std::string &cppitem_name)
TCppScope_t GetScope(const std::string &scope_name)
R__EXTERN PyObject * gClass
R__EXTERN PyObject * gName
R__EXTERN PyObject * gMRO
R__EXTERN PyObject * gTypeCode
R__EXTERN PyObject * gCppName
PyObject * RemoveGUIEventInputHook()
Bool_t InitProxy(PyObject *module, PyTypeObject *pytype, const char *name)
Initialize a proxy class for use by python, and add it to the ROOT module.
void ErrMsgHandler(int level, Bool_t abort, const char *location, const char *msg)
Translate ROOT error/warning to python.
PyObject * PyErr_Occurred_WithGIL()
Re-acquire the GIL before calling PyErr_Occurred() in case it has been released; note that the p2....
Bool_t AddUsingToClass(PyObject *pyclass, const char *method)
Helper to add base class methods to the derived class one (this covers the 'using' cases,...
Bool_t AddBinaryOperator(PyObject *left, PyObject *right, const char *op, const char *label, const char *alt_label=NULL, bool lazy=false)
Install the named operator (op) into the left object's class if such a function exists as a global ov...
std::string MapOperatorName(const std::string &name, Bool_t bTakesParames)
Map the given C++ operator name on the python equivalent.
PyObject * InstallGUIEventInputHook()
const std::string Compound(const std::string &name)
Break down the compound of a fully qualified type name.
int GetBuffer(PyObject *pyobject, char tc, int size, void *&buf, Bool_t check=kTRUE)
Retrieve a linear buffer pointer from the given pyobject.
PyObject * BuildTemplateName(PyObject *pyname, PyObject *tpArgs, int argoff, PyObject *args=nullptr, ArgPreference=kNone, int *pcnt=nullptr, bool inferredTypes=false)
Helper to construct the "< type, type, ... >" part of a templated name (either for a class as in Make...
Bool_t AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Add the given function to the class under name 'label'.
void ErrMsgCallback(char *msg)
Translate CINT error/warning into python equivalent.
Py_ssize_t ArraySize(const std::string &name)
Extract size from an array type, if available.
void * CreateWrapperMethod(PyObject *pyfunc, Long_t user, const char *retType, const std::vector< std::string > &signature, const char *callback)
Compile a function on the fly and return a function pointer for use on C-APIs.
const std::string ClassName(PyObject *pyobj)
Retrieve the class name from the given python object (which may be just an instance of the class).
R__EXTERN dict_lookup_func gDictLookupOrg
Bool_t ObjectProxy_Check(T *object)
ULong64_t PyLongOrInt_AsULong64(PyObject *pyobject)
Convert <pyobject> to C++ unsigned long long, with bounds checking.
MethodProxy * MethodProxy_New(const std::string &name, std::vector< PyCallable * > &methods)
Bool_t MethodProxy_Check(T *object)
R__EXTERN Bool_t gDictLookupActive
ULong_t PyLongOrInt_AsULong(PyObject *pyobject)
PyObject * TCustomInstanceMethod_New(PyObject *func, PyObject *self, PyObject *pyclass)
std::string ResolveTypedef(const char *tname, bool resolveAll=false)