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 )
329 Py_DECREF( pyclass );
337 PyObject* pyclass,
const char* op,
const char* label,
const char* alt )
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 )
375 if ( !
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;
471 Py_ssize_t nArgs = PyTuple_GET_SIZE( tpArgs );
472 for (
int i = argoff; i < nArgs; ++i ) {
474 PyObject* tn = PyTuple_GET_ITEM( tpArgs, i );
488 auto arg = PyTuple_GET_ITEM(args, i);
491 if (pcnt) *pcnt += 1;
494 }
else if (pref !=
kValue) {
502 if ( strcmp( tpNameStr,
"str" ) == 0 ) {
507 else if (inferredTypes && strcmp(tpNameStr,
"float") == 0) {
512 }
else if ( PyInt_Check( tn ) || PyLong_Check( tn ) || PyFloat_Check( tn ) ) {
516 PyObject* pystr = PyObject_Str( tn );
520 PyErr_SetString( PyExc_SyntaxError,
"could not get __cppname__ from provided template argument. Is it a str, class, type or int?" );
525 if ( i != nArgs - 1 )
544 if ( PyType_Ready( pytype ) < 0 )
549 if ( PyModule_AddObject( module, (
char*)
name, (
PyObject*)pytype ) < 0 ) {
568 PyBufferProcs* bufprocs =
Py_TYPE(pyobject)->tp_as_buffer;
570 PySequenceMethods* seqmeths =
Py_TYPE(pyobject)->tp_as_sequence;
571 if ( seqmeths != 0 && bufprocs != 0
572#
if PY_VERSION_HEX < 0x03000000
573 && bufprocs->bf_getwritebuffer != 0
574 && (*(bufprocs->bf_getsegcount))( pyobject, 0 ) == 1
576 && bufprocs->bf_getbuffer != 0
581#if PY_VERSION_HEX < 0x03000000
582 Py_ssize_t buflen = (*(bufprocs->bf_getwritebuffer))( pyobject, 0, &buf );
585 (*(bufprocs->bf_getbuffer))( pyobject, &bufinfo, PyBUF_WRITABLE );
586 buf = (
char*)bufinfo.buf;
588#
if PY_VERSION_HEX < 0x03010000
589 PyBuffer_Release( pyobject, &bufinfo );
591 PyBuffer_Release( &bufinfo );
595 if ( buf && check ==
kTRUE ) {
602 }
else if ( seqmeths->sq_length &&
603 (
int)(buflen / (*(seqmeths->sq_length))( pyobject )) == size ) {
606 }
else if ( buflen == size ) {
613 PyObject* pytype = 0, *pyvalue = 0, *pytrace = 0;
614 PyErr_Fetch( &pytype, &pyvalue, &pytrace );
616 (
char*)
"%s and given element size (%ld) do not match needed (%d)",
618 seqmeths->sq_length ? (
Long_t)(buflen / (*(seqmeths->sq_length))( pyobject )) : (
Long_t)buflen,
620 Py_DECREF( pyvalue );
621 PyErr_Restore( pytype, pyvalue2, pytrace );
636 if ( 8 <
name.size() &&
name.substr( 0, 8 ) ==
"operator" ) {
637 std::string op =
name.substr( 8, std::string::npos );
640 std::string::size_type start = 0, end = op.size();
641 while ( start < end && isspace( op[ start ] ) ) ++start;
642 while ( start < end && isspace( op[ end-1 ] ) ) --end;
650 }
else if ( op ==
"*" ) {
652 return bTakesParams ?
"__mul__" :
"__deref__";
654 }
else if ( op ==
"+" ) {
656 return bTakesParams ?
"__add__" :
"__pos__";
658 }
else if ( op ==
"-" ) {
660 return bTakesParams ?
"__sub__" :
"__neg__";
662 }
else if ( op ==
"++" ) {
664 return bTakesParams ?
"__postinc__" :
"__preinc__";
666 }
else if ( op ==
"--" ) {
668 return bTakesParams ?
"__postdec__" :
"__predec__";
682 std::string cleanName =
name;
683 RemoveConst( cleanName );
686 for (
int ipos = (
int)cleanName.size()-1; 0 <= ipos; --ipos ) {
687 char c = cleanName[ipos];
688 if ( isspace(
c ) )
continue;
689 if ( isalnum(
c ) ||
c ==
'_' ||
c ==
'>' )
break;
706 std::string cleanName =
name;
707 RemoveConst( cleanName );
709 if ( cleanName[cleanName.size()-1] ==
']' ) {
710 std::string::size_type idx = cleanName.rfind(
'[' );
711 if ( idx != std::string::npos ) {
712 const std::string asize = cleanName.substr( idx+1, cleanName.size()-2 );
713 return strtoul( asize.c_str(), NULL, 0 );
726 std::string clname =
"<unknown>";
728 if ( pyclass != 0 ) {
744 Py_DECREF( pyclass );
845 static const char* emptyString =
"";
846 if (!location) location = emptyString;
854 PyErr_WarnExplicit( NULL, (
char*)msg, (
char*)location, 0, (
char*)
"ROOT", NULL );
870 const char* retType,
const std::vector<std::string>& signature,
const char* callback )
874 if ( ! PyCallable_Check( pyfunc ) )
883 std::ostringstream funcName;
884 funcName <<
"pyrootGenFun" << fid;
887 std::ostringstream sigDecl, argsig;
888 std::vector<std::string>::size_type nargs = signature.size();
889 for ( std::vector<std::string>::size_type i = 0; i < nargs; ++i ) {
890 sigDecl << signature[i] <<
" a" << i;
891 argsig <<
", a" << i;
892 if ( i != nargs-1 ) sigDecl <<
", ";
896 std::ostringstream declCode;
897 declCode <<
"namespace PyROOT { "
898 << retType <<
" " << callback <<
"(void*, Long_t, " << sigDecl.str() <<
"); }\n"
899 << retType <<
" " << funcName.str() <<
"(" << sigDecl.str()
900 <<
") { void* v0 = (void*)" << (
void*)pyfunc <<
"; "
901 <<
"return PyROOT::" << callback <<
"(v0, " << user << argsig.str() <<
"); }";
907 std::ostringstream fptrCode;
908 fptrCode <<
"void* pyrootPtrVar" << fid <<
" = (void*)" << funcName.str()
909 <<
"; pyrootPtrVar" << fid <<
";";
912 void* fptr = (
void*)
gInterpreter->ProcessLineSynch( fptrCode.str().c_str() );
914 PyErr_SetString( PyExc_SyntaxError,
"could not generate C++ callback wrapper" );
926#if PY_VERSION_HEX >= 0x02030000
927 PyGILState_STATE gstate = PyGILState_Ensure();
929 PyGILState_Release( gstate );
931 if ( PyThreadState_GET() )
932 return PyErr_Occurred();
942 static int (*sOldInputHook)() = NULL;
943 static PyThreadState* sInputHookEventThreadState = NULL;
945 static int EventInputHook()
949 PyEval_RestoreThread( sInputHookEventThreadState );
953 if ( sOldInputHook )
return sOldInputHook();
962 if ( PyOS_InputHook && PyOS_InputHook != &EventInputHook )
963 sOldInputHook = PyOS_InputHook;
965 sInputHookEventThreadState = PyThreadState_Get();
967 PyOS_InputHook = (int (*)())&EventInputHook;
968 Py_INCREF( Py_None );
975 PyOS_InputHook = sOldInputHook;
976 sInputHookEventThreadState = NULL;
978 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.
Bool_t AddBinaryOperator(PyObject *left, PyObject *right, const char *op, const char *label, const char *alt_label=NULL)
Install the named operator (op) into the left object's class if such a function exists as a global ov...
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,...
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)