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 )
342 Py_DECREF( pyname ); pyname = 0;
351 const char* op,
TClass* klass = 0 ) {
352 std::string opname =
"operator";
354 std::string
proto = lcname +
", " + rcname;
361 return (
Cppyy::TCppMethod_t)klass->GetMethodWithPrototype( opname.c_str(), proto.c_str() );
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 for (
int i = argoff; i < nArgs; ++i ) {
473 PyObject* tn = PyTuple_GET_ITEM( args, i );
490 }
else if ( PyInt_Check( tn ) || PyLong_Check( tn ) || PyFloat_Check( tn ) ) {
494 PyObject* pystr = PyObject_Str( tn );
498 PyErr_SetString( PyExc_SyntaxError,
"could not get __cppname__ from provided template argument. Is it a str, class, type or int?" );
503 if ( i != nArgs - 1 )
522 if ( PyType_Ready( pytype ) < 0 )
527 if ( PyModule_AddObject( module, (
char*)name, (
PyObject*)pytype ) < 0 ) {
546 PyBufferProcs* bufprocs =
Py_TYPE(pyobject)->tp_as_buffer;
548 PySequenceMethods* seqmeths =
Py_TYPE(pyobject)->tp_as_sequence;
549 if ( seqmeths != 0 && bufprocs != 0
550 #
if PY_VERSION_HEX < 0x03000000
551 && bufprocs->bf_getwritebuffer != 0
552 && (*(bufprocs->bf_getsegcount))( pyobject, 0 ) == 1
554 && bufprocs->bf_getbuffer != 0
559 #if PY_VERSION_HEX < 0x03000000 560 Py_ssize_t buflen = (*(bufprocs->bf_getwritebuffer))( pyobject, 0, &buf );
563 (*(bufprocs->bf_getbuffer))( pyobject, &bufinfo, PyBUF_WRITABLE );
564 buf = (
char*)bufinfo.buf;
566 #
if PY_VERSION_HEX < 0x03010000
567 PyBuffer_Release( pyobject, &bufinfo );
569 PyBuffer_Release( &bufinfo );
573 if ( buf && check ==
kTRUE ) {
580 }
else if ( seqmeths->sq_length &&
581 (
int)(buflen / (*(seqmeths->sq_length))( pyobject )) == size ) {
584 }
else if ( buflen == size ) {
591 PyObject* pytype = 0, *pyvalue = 0, *pytrace = 0;
592 PyErr_Fetch( &pytype, &pyvalue, &pytrace );
594 (
char*)
"%s and given element size (%ld) do not match needed (%d)",
596 seqmeths->sq_length ? (
Long_t)(buflen / (*(seqmeths->sq_length))( pyobject )) : (
Long_t)buflen,
598 Py_DECREF( pyvalue );
599 PyErr_Restore( pytype, pyvalue2, pytrace );
614 if ( 8 < name.size() && name.substr( 0, 8 ) ==
"operator" ) {
615 std::string op = name.substr( 8, std::string::npos );
618 std::string::size_type start = 0, end = op.size();
619 while ( start < end && isspace( op[ start ] ) ) ++start;
620 while ( start < end && isspace( op[ end-1 ] ) ) --end;
628 }
else if ( op ==
"*" ) {
630 return bTakesParams ?
"__mul__" :
"__deref__";
632 }
else if ( op ==
"+" ) {
634 return bTakesParams ?
"__add__" :
"__pos__";
636 }
else if ( op ==
"-" ) {
638 return bTakesParams ?
"__sub__" :
"__neg__";
640 }
else if ( op ==
"++" ) {
642 return bTakesParams ?
"__postinc__" :
"__preinc__";
644 }
else if ( op ==
"--" ) {
646 return bTakesParams ?
"__postdec__" :
"__predec__";
660 std::string cleanName =
name;
661 RemoveConst( cleanName );
663 std::string compound =
"";
664 for (
int ipos = (
int)cleanName.size()-1; 0 <= ipos; --ipos ) {
665 char c = cleanName[ipos];
666 if ( isspace( c ) )
continue;
667 if ( isalnum( c ) || c ==
'_' || c ==
'>' )
break;
669 compound = c + compound;
673 if ( compound ==
"]" )
684 std::string cleanName =
name;
685 RemoveConst( cleanName );
687 if ( cleanName[cleanName.size()-1] ==
']' ) {
688 std::string::size_type idx = cleanName.rfind(
'[' );
689 if ( idx != std::string::npos ) {
690 const std::string asize = cleanName.substr( idx+1, cleanName.size()-2 );
691 return strtoul( asize.c_str(), NULL, 0 );
704 std::string clname =
"<unknown>";
706 if ( pyclass != 0 ) {
721 Py_DECREF( pyclass );
822 static const char* emptyString =
"";
823 if (!location) location = emptyString;
831 PyErr_WarnExplicit( NULL, (
char*)msg, (
char*)location, 0, (
char*)
"ROOT", NULL );
847 const char* retType,
const std::vector<std::string>& signature,
const char* callback )
851 if ( ! PyCallable_Check( pyfunc ) )
860 std::ostringstream funcName;
861 funcName <<
"pyrootGenFun" << fid;
864 std::ostringstream sigDecl, argsig;
865 std::vector<std::string>::size_type nargs = signature.size();
866 for ( std::vector<std::string>::size_type i = 0; i < nargs; ++i ) {
867 sigDecl << signature[i] <<
" a" << i;
868 argsig <<
", a" << i;
869 if ( i != nargs-1 ) sigDecl <<
", ";
873 std::ostringstream declCode;
874 declCode <<
"namespace PyROOT { " 875 << retType <<
" " << callback <<
"(void*, Long_t, " << sigDecl.str() <<
"); }\n" 876 << retType <<
" " << funcName.str() <<
"(" << sigDecl.str()
877 <<
") { void* v0 = (void*)" << (
void*)pyfunc <<
"; " 878 <<
"return PyROOT::" << callback <<
"(v0, " << user << argsig.str() <<
"); }";
884 std::ostringstream fptrCode;
885 fptrCode <<
"void* pyrootPtrVar" << fid <<
" = (void*)" << funcName.str()
886 <<
"; pyrootPtrVar" << fid <<
";";
889 void* fptr = (
void*)
gInterpreter->ProcessLineSynch( fptrCode.str().c_str() );
891 PyErr_SetString( PyExc_SyntaxError,
"could not generate C++ callback wrapper" );
903 #if PY_VERSION_HEX >= 0x02030000 904 PyGILState_STATE gstate = PyGILState_Ensure();
906 PyGILState_Release( gstate );
908 if ( PyThreadState_GET() )
909 return PyErr_Occurred();
919 static int (*sOldInputHook)() = NULL;
920 static PyThreadState* sInputHookEventThreadState = NULL;
922 static int EventInputHook()
926 PyEval_RestoreThread( sInputHookEventThreadState );
930 if ( sOldInputHook )
return sOldInputHook();
939 if ( PyOS_InputHook && PyOS_InputHook != &EventInputHook )
940 sOldInputHook = PyOS_InputHook;
942 sInputHookEventThreadState = PyThreadState_Get();
944 PyOS_InputHook = (int (*)())&EventInputHook;
945 Py_INCREF( Py_None );
952 PyOS_InputHook = sOldInputHook;
953 sInputHookEventThreadState = NULL;
955 Py_INCREF( Py_None );
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.
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...
#define PyROOT_PyUnicode_FromString
PyDictEntry *(* dict_lookup_func)(PyDictObject *, PyObject *, Long_t)
virtual Bool_t ProcessEvents()
Process pending events (GUI, timers, sockets).
R__EXTERN Int_t gErrorIgnoreLevel
PyObject * TCustomInstanceMethod_New(PyObject *func, PyObject *self, PyObject *pyclass)
Dictionary for function template This class describes one single function template.
void DefaultErrorHandler(int level, Bool_t abort, const char *location, const char *msg)
The default error handler function.
PyObject * RemoveGUIEventInputHook()
MethodProxy * MethodProxy_New(const std::string &name, std::vector< PyCallable * > &methods)
R__EXTERN dict_lookup_func gDictLookupOrg
PyObject * BuildTemplateName(PyObject *pyname, PyObject *args, int argoff)
Helper to construct the "< type, type, ... >" part of a templated name (either for a class as in Make...
R__EXTERN TApplication * gApplication
R__EXTERN Bool_t gDictLookupActive
TClass * GetClass() const
#define PyROOT_PyUnicode_FromFormat
#define PyROOT_PyUnicode_Append
std::string ResolveName(const std::string &cppitem_name)
std::string MapOperatorName(const std::string &name, Bool_t bTakesParames)
Map the given C++ operator name on the python equivalent.
#define PyROOT_PyUnicode_GetSize
R__EXTERN PyObject * gMRO
std::string ResolveTypedef(const char *tname, bool resolveAll=false)
ClassInfo_t * GetClassInfo() const
const std::string ClassName(PyObject *pyobj)
Retrieve the class name from the given python object (which may be just an instance of the class)...
#define PyROOT_PyUnicode_AsString
PyObject * PyErr_Occurred_WithGIL()
Re-acquire the GIL before calling PyErr_Occurred() in case it has been released; note that the p2...
std::map< std::string, std::string > TC2POperatorMapping_t
static TC2POperatorMapping_t gC2POperatorMapping
R__EXTERN TVirtualMutex * gGlobalMutex
ULong_t PyLongOrInt_AsULong(PyObject *pyobject)
void ErrMsgHandler(int level, Bool_t abort, const char *location, const char *msg)
Translate ROOT error/warning to python.
Bool_t ObjectProxy_Check(T *object)
R__EXTERN PyObject * gClass
R__EXTERN TSystem * gSystem
ULong64_t PyLongOrInt_AsULong64(PyObject *pyobject)
Convert <pyobject> to C++ unsigned long long, with bounds checking.
The ROOT global object gROOT contains a list of all defined classes.
#define PyROOT_PyUnicode_AppendAndDel
PyObject * InstallGUIEventInputHook()
TCppScope_t GetScope(const std::string &scope_name)
R__EXTERN PyObject * gName
void AddMethod(PyCallable *pc)
Fill in the data of a freshly created method proxy.
R__EXTERN PyObject * gTypeCode
unsigned long long ULong64_t
Bool_t AddToClass(PyObject *pyclass, const char *label, PyCFunction cfunc, int flags=METH_VARARGS)
Add the given function to the class under name 'label'.
#define PyROOT_PyUnicode_Check
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
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.
Bool_t AddUsingToClass(PyObject *pyclass, const char *method)
Helper to add base class methods to the derived class one (this covers the 'using' cases...
R__EXTERN PyObject * gCppName
TFunctionTemplate * GetFunctionTemplate(const char *name)
TClassRef is used to implement a permanent reference to a TClass object.
int GetBuffer(PyObject *pyobject, char tc, int size, void *&buf, Bool_t check=kTRUE)
Retrieve a linear buffer pointer from the given pyobject.
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.
Bool_t MethodProxy_Check(T *object)
Py_ssize_t ArraySize(const std::string &name)
Extract size from an array type, if available.
void ErrMsgCallback(char *msg)
Translate CINT error/warning into python equivalent.
TMethod * GetMethodAny(const char *method)
Return pointer to method without looking at parameters.
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'.
TMethod * GetMethodWithPrototype(const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
Find the method with a given prototype.
const std::string Compound(const std::string &name)
Break down the compound of a fully qualified type name.