PyObject_SetAttrString() private méthode

private PyObject_SetAttrString ( IntPtr pointer, string name, IntPtr value ) : int
pointer IntPtr
name string
value IntPtr
Résultat int
Exemple #1
0
        /// <summary>
        /// Restore the __import__ hook.
        /// </summary>
        static void RestoreImport()
        {
            IntPtr builtins = GetNewRefToBuiltins();

            int res = Runtime.PyObject_SetAttrString(builtins, "__import__", py_import);

            PythonException.ThrowIfIsNotZero(res);
            Runtime.XDecref(py_import);
            py_import = IntPtr.Zero;

            hook.Release();
            hook = null;

            Runtime.XDecref(builtins);
        }
Exemple #2
0
        /// <summary>
        /// Cleanup resources upon shutdown of the Python runtime.
        /// </summary>
        internal static void Shutdown()
        {
            if (Runtime.Py_IsInitialized() != 0)
            {
                Runtime.XDecref(py_clr_module);
                Runtime.XDecref(root.pyHandle);

                // Re-install the original import function
                IntPtr dict = Runtime.PyImport_GetModuleDict();
                IntPtr mod  = Runtime.IsPython3
                    ? Runtime.PyImport_ImportModule("builtins")
                    : Runtime.PyDict_GetItemString(dict, "__builtin__");
                Runtime.PyObject_SetAttrString(mod, "__import__", py_import);
                Runtime.XDecref(py_import);
            }
        }
Exemple #3
0
        /// <summary>
        /// Initialize just the __import__ hook itself.
        /// </summary>
        static void InitImport()
        {
            // We replace the built-in Python __import__ with our own: first
            // look in CLR modules, then if we don't find any call the default
            // Python __import__.
            IntPtr builtins = GetNewRefToBuiltins();

            py_import = Runtime.PyObject_GetAttrString(builtins, "__import__");
            PythonException.ThrowIfIsNull(py_import);

            hook = new MethodWrapper(typeof(ImportHook), "__import__", "TernaryFunc");
            int res = Runtime.PyObject_SetAttrString(builtins, "__import__", hook.ptr);

            PythonException.ThrowIfIsNotZero(res);

            Runtime.XDecref(builtins);
        }
Exemple #4
0
        /// <summary>
        /// SetAttr Method
        /// </summary>
        /// <remarks>
        /// Set an attribute of the object with the given name and value. This
        /// method throws a PythonException if the attribute set fails.
        /// </remarks>
        public void SetAttr(string name, PyObject value)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            int r = Runtime.PyObject_SetAttrString(obj, name, value.obj);

            if (r < 0)
            {
                throw new PythonException();
            }
        }
Exemple #5
0
        //===================================================================
        // Initialization performed on startup of the Python runtime.
        //===================================================================

        internal static void Initialize()
        {
            // Initialize the Python <--> CLR module hook. We replace the
            // built-in Python __import__ with our own. This isn't ideal,
            // but it provides the most "Pythonic" way of dealing with CLR
            // modules (Python doesn't provide a way to emulate packages).
            IntPtr dict = Runtime.PyImport_GetModuleDict();

#if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35)
            IntPtr mod = Runtime.PyImport_ImportModule("builtins");
            py_import = Runtime.PyObject_GetAttrString(mod, "__import__");
#else
            IntPtr mod = Runtime.PyDict_GetItemString(dict, "__builtin__");
            py_import = Runtime.PyObject_GetAttrString(mod, "__import__");
#endif
            hook = new MethodWrapper(typeof(ImportHook), "__import__", "TernaryFunc");
            Runtime.PyObject_SetAttrString(mod, "__import__", hook.ptr);
            Runtime.Decref(hook.ptr);

            root = new CLRModule();

#if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35)
            // create a python module with the same methods as the clr module-like object
            module_def    = ModuleDefOffset.AllocModuleDef("clr");
            py_clr_module = Runtime.PyModule_Create2(module_def, 3);

            // both dicts are borrowed references
            IntPtr mod_dict = Runtime.PyModule_GetDict(py_clr_module);
            IntPtr clr_dict = Runtime._PyObject_GetDictPtr(root.pyHandle); // PyObject**
            clr_dict = (IntPtr)Marshal.PtrToStructure(clr_dict, typeof(IntPtr));

            Runtime.PyDict_Update(mod_dict, clr_dict);
            Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module);
            Runtime.PyDict_SetItemString(dict, "clr", py_clr_module);
#else
            Runtime.Incref(root.pyHandle); // we are using the module two times
            Runtime.PyDict_SetItemString(dict, "CLR", root.pyHandle);
            Runtime.PyDict_SetItemString(dict, "clr", root.pyHandle);
#endif
        }
Exemple #6
0
        internal static IntPtr GenerateExceptionClass(IntPtr real)
        {
            if (real == ns_exc)
            {
                return(os_exc);
            }

            IntPtr nbases = Runtime.PyObject_GetAttrString(real, "__bases__");

            if (Runtime.PyTuple_Size(nbases) != 1)
            {
                throw new SystemException("Invalid __bases__");
            }
            IntPtr nsbase = Runtime.PyTuple_GetItem(nbases, 0);

            Runtime.Decref(nbases);

            IntPtr osbase   = GetExceptionClassWrapper(nsbase);
            IntPtr baselist = Runtime.PyTuple_New(1);

            Runtime.Incref(osbase);
            Runtime.PyTuple_SetItem(baselist, 0, osbase);
            IntPtr name = Runtime.PyObject_GetAttrString(real, "__name__");

            IntPtr dict = Runtime.PyDict_New();
            IntPtr mod  = Runtime.PyObject_GetAttrString(real, "__module__");

            Runtime.PyDict_SetItemString(dict, "__module__", mod);
            Runtime.Decref(mod);

            IntPtr subc = Runtime.PyClass_New(baselist, dict, name);

            Runtime.Decref(baselist);
            Runtime.Decref(dict);
            Runtime.Decref(name);

            Runtime.PyObject_SetAttrString(subc, "_class", real);
            return(subc);
        }
Exemple #7
0
        /// <summary>
        /// SetError Method
        /// </summary>
        /// <remarks>
        /// Sets the current Python exception given a CLR exception
        /// object. The CLR exception instance is wrapped as a Python
        /// object, allowing it to be handled naturally from Python.
        /// </remarks>
        public static bool SetError(Exception e)
        {
            Debug.Assert(e is not null);

            // Because delegates allow arbitrary nesting of Python calling
            // managed calling Python calling... etc. it is possible that we
            // might get a managed exception raised that is a wrapper for a
            // Python exception. In that case we'd rather have the real thing.

            var pe = e as PythonException;

            if (pe != null)
            {
                pe.Restore();
                return(true);
            }

            using var instance = Converter.ToPythonReference(e);
            if (instance.IsNull())
            {
                return(false);
            }

            var exceptionInfo = ExceptionDispatchInfo.Capture(e);

            using var pyInfo = Converter.ToPythonReference(exceptionInfo);

            if (Runtime.PyObject_SetAttrString(instance, DispatchInfoAttribute, pyInfo) != 0)
            {
                return(false);
            }

            Debug.Assert(Runtime.PyObject_TypeCheck(instance, new BorrowedReference(BaseException)));

            var type = Runtime.PyObject_TYPE(instance);

            Runtime.PyErr_SetObject(type, instance);
            return(true);
        }
Exemple #8
0
        /// <summary>
        /// Initialization performed on startup of the Python runtime.
        /// </summary>
        internal static void Initialize()
        {
            // Console.WriteLine("----------IMPORT HOOK INITIALIzE");
            // Initialize the Python <--> CLR module hook. We replace the
            // built-in Python __import__ with our own. This isn't ideal,
            // but it provides the most "Pythonic" way of dealing with CLR
            // modules (Python doesn't provide a way to emulate packages).
            IntPtr dict = Runtime.PyImport_GetModuleDict();

            IntPtr mod = Runtime.IsPython3
                ? Runtime.PyImport_ImportModule("builtins")
                : Runtime.PyDict_GetItemString(dict, "__builtin__");

            py_import = Runtime.PyObject_GetAttrString(mod, "__import__");
            hook      = new MethodWrapper(typeof(ImportHook), "__import__", "TernaryFunc");
            Runtime.PyObject_SetAttrString(mod, "__import__", hook.ptr);
            Runtime.XDecref(hook.ptr);

            root = new CLRModule();

#if PYTHON3
            // create a python module with the same methods as the clr module-like object
            InitializeModuleDef();
            py_clr_module = Runtime.PyModule_Create2(module_def, 3);

            // both dicts are borrowed references
            IntPtr mod_dict = Runtime.PyModule_GetDict(py_clr_module);
            IntPtr clr_dict = Runtime._PyObject_GetDictPtr(root.pyHandle); // PyObject**
            clr_dict = (IntPtr)Marshal.PtrToStructure(clr_dict, typeof(IntPtr));

            Runtime.PyDict_Update(mod_dict, clr_dict);
#elif PYTHON2
            Runtime.XIncref(root.pyHandle); // we are using the module two times
            py_clr_module = root.pyHandle;  // Alias handle for PY2/PY3
#endif
            Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module);
            Runtime.PyDict_SetItemString(dict, "clr", py_clr_module);
        }
Exemple #9
0
        /// <remarks>
        /// the lines
        /// // XXX - hack to raise a compatible old-style exception ;(
        /// if (Runtime.wrap_exceptions) {
        ///     CallOneOfTheseMethods();
        ///
        /// </remarks>
        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" +
                "    #@property\n" +
                "    def message(self):\n" +
                "        return self.Message\n" +
                "    message = property(message)\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" +
                "    def __repr__(self):\n" +
                "        inner = self.__dict__.get('_inner')\n" +
                "        msg = getattr(inner, 'Message', '')\n" +
                "        name = self.__class__.__name__\n" +
                "        return '%s(\\'%s\\',)' % (name, msg) \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 result = Runtime.PyRun_String(code, flag, dict, dict);

            Exceptions.ErrorCheck(result);
            Runtime.Decref(result);

            os_exc = Runtime.PyDict_GetItemString(dict, "Exception");
            Runtime.PyObject_SetAttrString(os_exc, "_class", ns_exc);
            Runtime.PyErr_Clear();
        }