//=================================================================== // Initialization performed on startup of the Python runtime. //=================================================================== internal static void Initialize() { #if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35) exceptions_module = Runtime.PyImport_ImportModule("builtins"); #else exceptions_module = Runtime.PyImport_ImportModule("exceptions"); #endif Exceptions.ErrorCheck(exceptions_module); warnings_module = Runtime.PyImport_ImportModule("warnings"); Exceptions.ErrorCheck(warnings_module); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(exceptions_module, fi.Name); if (op != IntPtr.Zero) { fi.SetValue(type, op); } else { fi.SetValue(type, IntPtr.Zero); DebugUtil.Print("Unknown exception: " + fi.Name); } } Runtime.PyErr_Clear(); }
/// <summary> /// Initialization performed on startup of the Python runtime. /// </summary> internal static void Initialize() { string exceptionsModuleName = Runtime.IsPython3 ? "builtins" : "exceptions"; exceptions_module = Runtime.PyImport_ImportModule(exceptionsModuleName); Exceptions.ErrorCheck(exceptions_module); warnings_module = Runtime.PyImport_ImportModule("warnings"); Exceptions.ErrorCheck(warnings_module); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(exceptions_module, fi.Name); if (op != IntPtr.Zero) { fi.SetValue(type, op); } else { fi.SetValue(type, IntPtr.Zero); DebugUtil.Print($"Unknown exception: {fi.Name}"); } } Runtime.PyErr_Clear(); }
protected override void OnSave(InterDomainContext context) { base.OnSave(context); System.Diagnostics.Debug.Assert(dict == GetObjectDict(pyHandle)); foreach (var attr in cache.Values) { Runtime.XIncref(attr.pyHandle); } // Decref twice in tp_clear, equilibrate them. Runtime.XIncref(dict); Runtime.XIncref(dict); // destroy the cache(s) foreach (var pair in cache) { if ((Runtime.PyDict_DelItemString(DictRef, pair.Key) == -1) && (Exceptions.ExceptionMatches(Exceptions.KeyError))) { // Trying to remove a key that's not in the dictionary // raises an error. We don't care about it. Runtime.PyErr_Clear(); } else if (Exceptions.ErrorOccurred()) { throw new PythonException(); } pair.Value.DecrRefCount(); } cache.Clear(); }
internal static void SetupExceptionHack() { ns_exc = ClassManager.GetClass(typeof(Exception)).pyHandle; cache = new Hashtable(); string code = "import exceptions\n" + "class Exception(exceptions.Exception):\n" + " _class = None\n" + " _inner = None\n" + "\n" + " def __init__(self, *args, **kw):\n" + " inst = self.__class__._class(*args, **kw)\n" + " self.__dict__['_inner'] = inst\n" + " exceptions.Exception.__init__(self, *args, **kw)\n" + "\n" + " def __getattr__(self, name, _marker=[]):\n" + " inner = self.__dict__['_inner']\n" + " v = getattr(inner, name, _marker)\n" + " if v is not _marker:\n" + " return v\n" + " v = self.__dict__.get(name, _marker)\n" + " if v is not _marker:\n" + " return v\n" + " raise AttributeError(name)\n" + "\n" + " def __setattr__(self, name, value):\n" + " inner = self.__dict__['_inner']\n" + " setattr(inner, name, value)\n" + "\n" + " def __str__(self):\n" + " inner = self.__dict__.get('_inner')\n" + " msg = getattr(inner, 'Message', '')\n" + " st = getattr(inner, 'StackTrace', '')\n" + " st = st and '\\n' + st or ''\n" + " return msg + st\n" + "\n"; IntPtr dict = Runtime.PyDict_New(); IntPtr builtins = Runtime.PyEval_GetBuiltins(); Runtime.PyDict_SetItemString(dict, "__builtins__", builtins); IntPtr namestr = Runtime.PyString_FromString("System"); Runtime.PyDict_SetItemString(dict, "__name__", namestr); Runtime.Decref(namestr); Runtime.PyDict_SetItemString(dict, "__file__", Runtime.PyNone); Runtime.PyDict_SetItemString(dict, "__doc__", Runtime.PyNone); IntPtr flag = Runtime.Py_file_input; IntPtr done = Runtime.PyRun_String(code, flag, dict, dict); os_exc = Runtime.PyDict_GetItemString(dict, "Exception"); Runtime.PyObject_SetAttrString(os_exc, "_class", ns_exc); Runtime.PyErr_Clear(); }
/// <summary> /// IsSubclass Method /// </summary> /// <remarks> /// Return true if the object is identical to or derived from the /// given Python type or class. This method always succeeds. /// </remarks> public bool IsSubclass(PyObject typeOrClass) { int r = Runtime.PyObject_IsSubclass(obj, typeOrClass.obj); if (r < 0) { Runtime.PyErr_Clear(); return(false); } return(r != 0); }
/// <summary> /// GetAttr Method /// </summary> /// <remarks> /// Returns the named attribute of the Python object, or the given /// default object if the attribute access fails. The name argument /// is a PyObject wrapping a Python string or unicode object. /// </remarks> public PyObject GetAttr(PyObject name, PyObject _default) { IntPtr op = Runtime.PyObject_GetAttr(obj, name.obj); if (op == IntPtr.Zero) { Runtime.PyErr_Clear(); return(_default); } return(new PyObject(op)); }
/// <summary> /// Length Method /// </summary> /// <remarks> /// Returns the length for objects that support the Python sequence /// protocol, or 0 if the object does not support the protocol. /// </remarks> public virtual int Length() { int s = Runtime.PyObject_Size(obj); if (s < 0) { Runtime.PyErr_Clear(); return(0); } return(s); }
/// <summary> /// Index Method /// </summary> /// /// <remarks> /// Return the index of the given item in the sequence, or -1 if /// the item does not appear in the sequence. /// </remarks> public int Index(PyObject item) { int r = Runtime.PySequence_Index(obj, item.obj); if (r < 0) { Runtime.PyErr_Clear(); return(-1); } return(r); }
/// <summary> /// GetAttr Method /// </summary> /// <remarks> /// Returns the named attribute of the Python object, or the given /// default object if the attribute access fails. The name argument /// is a PyObject wrapping a Python string or unicode object. /// </remarks> public PyObject GetAttr(PyObject name, PyObject _default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } IntPtr op = Runtime.PyObject_GetAttr(obj, name.obj); if (op == IntPtr.Zero) { Runtime.PyErr_Clear(); return(_default); } return(new PyObject(op)); }
/// <summary> /// IsSubclass Method /// </summary> /// <remarks> /// Return true if the object is identical to or derived from the /// given Python type or class. This method always succeeds. /// </remarks> public bool IsSubclass(PyObject typeOrClass) { if (typeOrClass == null) { throw new ArgumentNullException(nameof(typeOrClass)); } int r = Runtime.PyObject_IsSubclass(obj, typeOrClass.obj); if (r < 0) { Runtime.PyErr_Clear(); return(false); } return(r != 0); }
internal bool IsSubclass(BorrowedReference typeOrClass) { if (typeOrClass.IsNull) { throw new ArgumentNullException(nameof(typeOrClass)); } int r = Runtime.PyObject_IsSubclass(Reference, typeOrClass); if (r < 0) { Runtime.PyErr_Clear(); return(false); } return(r != 0); }
internal static void SaveRuntimeData(RuntimeDataStorage storage) { var contexts = storage.AddValue("contexts", new Dictionary <IntPtr, InterDomainContext>()); storage.AddValue("cache", cache); foreach (var cls in cache) { if (!cls.Key.Valid) { // Don't serialize an invalid class continue; } // This incref is for cache to hold the cls, // thus no need for decreasing it at RestoreRuntimeData. Runtime.XIncref(cls.Value.pyHandle); var context = contexts[cls.Value.pyHandle] = new InterDomainContext(); cls.Value.Save(context); // Remove all members added in InitBaseClass. // this is done so that if domain reloads and a member of a // reflected dotnet class is removed, it is removed from the // Python object's dictionary tool; thus raising an AttributeError // instead of a TypeError. // Classes are re-initialized on in RestoreRuntimeData. var dict = new BorrowedReference(Marshal.ReadIntPtr(cls.Value.tpHandle, TypeOffset.tp_dict)); foreach (var member in cls.Value.dotNetMembers) { // No need to decref the member, the ClassBase instance does // not own the reference. if ((Runtime.PyDict_DelItemString(dict, member) == -1) && (Exceptions.ExceptionMatches(Exceptions.KeyError))) { // Trying to remove a key that's not in the dictionary // raises an error. We don't care about it. Runtime.PyErr_Clear(); } else if (Exceptions.ErrorOccurred()) { throw new PythonException(); } } // We modified the Type object, notify it we did. Runtime.PyType_Modified(cls.Value.tpHandle); } }
//==================================================================== // Metatype __call__ implementation. This is needed to ensure correct // initialization (__init__ support), because the tp_call we inherit // from PyType_Type won't call __init__ for metatypes it doesnt know. //==================================================================== public static IntPtr tp_call(IntPtr tp, IntPtr args, IntPtr kw) { IntPtr func = Marshal.ReadIntPtr(tp, TypeOffset.tp_new); if (func == IntPtr.Zero) { return(Exceptions.RaiseTypeError("invalid object")); } IntPtr obj = NativeCall.Call_3(func, tp, args, kw); if (obj == IntPtr.Zero) { return(IntPtr.Zero); } IntPtr py__init__ = Runtime.PyString_FromString("__init__"); IntPtr type = Runtime.PyObject_TYPE(obj); IntPtr init = Runtime._PyType_Lookup(type, py__init__); Runtime.Decref(py__init__); Runtime.PyErr_Clear(); if (init != IntPtr.Zero) { IntPtr bound = Runtime.GetBoundArgTuple(obj, args); if (bound == IntPtr.Zero) { Runtime.Decref(obj); return(IntPtr.Zero); } IntPtr result = Runtime.PyObject_Call(init, bound, kw); Runtime.Decref(bound); if (result == IntPtr.Zero) { Runtime.Decref(obj); return(IntPtr.Zero); } Runtime.Decref(result); } return(obj); }
/// <summary> /// Initializes given object, or returns <c>false</c> and sets Python error on failure /// </summary> public virtual bool Init(BorrowedReference obj, BorrowedReference args, BorrowedReference kw) { // this just calls obj.__init__(*args, **kw) using var init = Runtime.PyObject_GetAttr(obj, PyIdentifier.__init__); Runtime.PyErr_Clear(); if (!init.IsNull()) { using var result = Runtime.PyObject_Call(init.Borrow(), args, kw); if (result.IsNull()) { return(false); } } return(true); }
#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable. /// <summary> /// Initialization performed on startup of the Python runtime. /// </summary> internal static void Initialize() { string exceptionsModuleName = "builtins"; exceptions_module = PyModule.Import(exceptionsModuleName); warnings_module = PyModule.Import("warnings"); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { using var op = Runtime.PyObject_GetAttrString(exceptions_module.obj, fi.Name); if ([email protected]()) { fi.SetValue(type, op.MoveToPyObject()); } else { fi.SetValue(type, null); DebugUtil.Print($"Unknown exception: {fi.Name}"); } } Runtime.PyErr_Clear(); }
//=================================================================== // Initialization performed on startup of the Python runtime. //=================================================================== internal static void Initialize() { IntPtr module = Runtime.PyImport_ImportModule("exceptions"); Type type = typeof(Exceptions); foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static)) { IntPtr op = Runtime.PyObject_GetAttrString(module, fi.Name); if (op != IntPtr.Zero) { fi.SetValue(type, op); } } Runtime.Decref(module); Runtime.PyErr_Clear(); if (Runtime.wrap_exceptions) { SetupExceptionHack(); } }
private static IntPtr CallInit(IntPtr obj, IntPtr args, IntPtr kw) { var init = Runtime.PyObject_GetAttr(obj, PyIdentifier.__init__); Runtime.PyErr_Clear(); if (init != IntPtr.Zero) { IntPtr result = Runtime.PyObject_Call(init, args, kw); Runtime.XDecref(init); if (result == IntPtr.Zero) { Runtime.XDecref(obj); return(IntPtr.Zero); } Runtime.XDecref(result); } return(obj); }
/// <summary> /// Metatype __call__ implementation. This is needed to ensure correct /// initialization (__init__ support), because the tp_call we inherit /// from PyType_Type won't call __init__ for metatypes it doesn't know. /// </summary> public static IntPtr tp_call(IntPtr tp, IntPtr args, IntPtr kw) { IntPtr func = Marshal.ReadIntPtr(tp, TypeOffset.tp_new); if (func == IntPtr.Zero) { return(Exceptions.RaiseTypeError("invalid object")); } IntPtr obj = NativeCall.Call_3(func, tp, args, kw); if (obj == IntPtr.Zero) { return(IntPtr.Zero); } var init = Runtime.PyObject_GetAttrString(obj, "__init__"); Runtime.PyErr_Clear(); if (init != IntPtr.Zero) { IntPtr result = Runtime.PyObject_Call(init, args, kw); Runtime.XDecref(init); if (result == IntPtr.Zero) { Runtime.XDecref(obj); return(IntPtr.Zero); } Runtime.XDecref(result); } return(obj); }
/// <summary> /// Clear Method /// </summary> /// <remarks> /// Clear any exception that has been set in the Python runtime. /// </remarks> public static void Clear() { Runtime.PyErr_Clear(); }
internal static void Shutdown() { Instance.DisposeAll(); Instance.CallPendingFinalizers(); Runtime.PyErr_Clear(); }
/// <summary> /// MethodBinding __call__ implementation. /// </summary> public static IntPtr tp_call(IntPtr ob, IntPtr args, IntPtr kw) { var self = (MethodBinding)GetManagedObject(ob); // This works around a situation where the wrong generic method is picked, // for example this method in the tests: string Overloaded<T>(int arg1, int arg2, string arg3) if (self.info != null) { if (self.info.IsGenericMethod) { var len = Runtime.PyTuple_Size(args); //FIXME: Never used Type[] sigTp = Runtime.PythonArgsToTypeArray(args, true); if (sigTp != null) { Type[] genericTp = self.info.GetGenericArguments(); MethodInfo betterMatch = MethodBinder.MatchSignatureAndParameters(self.m.info, genericTp, sigTp); if (betterMatch != null) { self.info = betterMatch; } } } } // This supports calling a method 'unbound', passing the instance // as the first argument. Note that this is not supported if any // of the overloads are static since we can't know if the intent // was to call the static method or the unbound instance method. var disposeList = new List <IntPtr>(); try { IntPtr target = self.target; if (target == IntPtr.Zero && !self.m.IsStatic()) { var len = Runtime.PyTuple_Size(args); if (len < 1) { Exceptions.SetError(Exceptions.TypeError, "not enough arguments"); return(IntPtr.Zero); } target = Runtime.PyTuple_GetItem(args, 0); Runtime.XIncref(target); disposeList.Add(target); args = Runtime.PyTuple_GetSlice(args, 1, len); disposeList.Add(args); } // if the class is a IPythonDerivedClass and target is not the same as self.targetType // (eg if calling the base class method) then call the original base class method instead // of the target method. IntPtr superType = IntPtr.Zero; if (Runtime.PyObject_TYPE(target) != self.targetType) { var inst = GetManagedObject(target) as CLRObject; if (inst?.inst is IPythonDerivedType) { var baseType = GetManagedObject(self.targetType) as ClassBase; if (baseType != null) { string baseMethodName = "_" + baseType.type.Name + "__" + self.m.name; IntPtr baseMethod = Runtime.PyObject_GetAttrString(target, baseMethodName); if (baseMethod != IntPtr.Zero) { var baseSelf = GetManagedObject(baseMethod) as MethodBinding; if (baseSelf != null) { self = baseSelf; } Runtime.XDecref(baseMethod); } else { Runtime.PyErr_Clear(); } } } } return(self.m.Invoke(target, args, kw, self.info)); } finally { foreach (IntPtr ptr in disposeList) { Runtime.XDecref(ptr); } } }