PyDict_Update() private method

private PyDict_Update ( IntPtr pointer, IntPtr other ) : int
pointer IntPtr
other IntPtr
return int
示例#1
0
        /// <summary>
        /// Initialization performed on startup of the Python runtime.
        /// </summary>
        internal static void Initialize()
        {
            InitImport();

            // Initialize the clr module and tell Python about it.
            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
            IntPtr dict = Runtime.PyImport_GetModuleDict();
            Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module);
            Runtime.PyDict_SetItemString(dict, "clr", py_clr_module);
        }
示例#2
0
        /// <summary>
        /// ImportAll Method
        /// </summary>
        /// <remarks>
        /// Import all variables of the scope into this scope.
        /// </remarks>
        public void ImportAll(PyScope scope)
        {
            int result = Runtime.PyDict_Update(variables, scope.variables);

            if (result < 0)
            {
                throw new PythonException();
            }
        }
示例#3
0
        /// <summary>
        /// Update Method
        /// </summary>
        /// <remarks>
        /// Update the dictionary from another dictionary.
        /// </remarks>
        public void Update(PyObject other)
        {
            int result = Runtime.PyDict_Update(Reference, other.Reference);

            if (result < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
        }
示例#4
0
        //===================================================================
        // Return the clr python module (new reference)
        //===================================================================
        public static IntPtr GetCLRModule(IntPtr?fromList = null)
        {
            root.InitializePreload();
#if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35)
            // update the module dictionary with the contents of the root dictionary
            root.LoadNames();
            IntPtr py_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(py_mod_dict, clr_dict);

            // find any items from the fromlist and get them from the root if they're not
            // aleady in the module dictionary
            if (fromList != null && fromList != IntPtr.Zero)
            {
                if (Runtime.PyTuple_Check(fromList.GetValueOrDefault()))
                {
                    Runtime.Incref(py_mod_dict);
                    using (PyDict mod_dict = new PyDict(py_mod_dict)) {
                        Runtime.Incref(fromList.GetValueOrDefault());
                        using (PyTuple from = new PyTuple(fromList.GetValueOrDefault())) {
                            foreach (PyObject item in from)
                            {
                                if (mod_dict.HasKey(item))
                                {
                                    continue;
                                }

                                string s = item.AsManagedObject(typeof(string)) as string;
                                if (null == s)
                                {
                                    continue;
                                }

                                ManagedType attr = root.GetAttribute(s, true);
                                if (null == attr)
                                {
                                    continue;
                                }

                                Runtime.Incref(attr.pyHandle);
                                using (PyObject obj = new PyObject(attr.pyHandle)) {
                                    mod_dict.SetItem(s, obj);
                                }
                            }
                        }
                    }
                }
            }

            Runtime.Incref(py_clr_module);
            return(py_clr_module);
#else
            Runtime.Incref(root.pyHandle);
            return(root.pyHandle);
#endif
        }
示例#5
0
        /// <summary>
        /// ImportAll Method
        /// </summary>
        /// <remarks>
        /// Import all variables in the dictionary into this scope.
        /// </remarks>
        public void ImportAll(PyDict dict)
        {
            int result = Runtime.PyDict_Update(variables, dict.obj);

            if (result < 0)
            {
                throw new PythonException();
            }
        }
示例#6
0
        /// <summary>
        /// Update Method
        /// </summary>
        ///
        /// <remarks>
        /// Update the dictionary from another dictionary.
        /// </remarks>
        public void Update(PyObject other)
        {
            int result = Runtime.PyDict_Update(obj, other.obj);

            if (result < 0)
            {
                throw new PythonException();
            }
        }
示例#7
0
        /// <summary>
        /// ImportAll Method
        /// </summary>
        /// <remarks>
        /// Import all variables in the dictionary into this scope.
        /// </remarks>
        public void ImportAll(PyDict dict)
        {
            int result = Runtime.PyDict_Update(VarsRef, dict.Reference);

            if (result < 0)
            {
                throw new PythonException();
            }
        }
示例#8
0
        /// <summary>
        /// ImportAll Method
        /// </summary>
        /// <remarks>
        /// Import all variables of the scope into this scope.
        /// </remarks>
        public void ImportAll(PyScope scope)
        {
            int result = Runtime.PyDict_Update(VarsRef, scope.VarsRef);

            if (result < 0)
            {
                throw new PythonException();
            }
        }
示例#9
0
        /// <summary>
        /// Initialization performed on startup of the Python runtime.
        /// </summary>
        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();

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

            if (mod == IntPtr.Zero)
            {
                throw new PythonException();
            }

            py_import = Runtime.PyObject_GetAttrString(mod, "__import__");
            if (py_import == IntPtr.Zero)
            {
                throw new PythonException();
            }

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

            if (Runtime.IsPython3)
            {
                // On Python3, PyImport_ImportModule got a new reference, so we need to decrease it.
                Runtime.Py_DecRef(mod);
            }

            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);
        }
示例#10
0
        /// <summary>
        /// Return the clr python module (new reference)
        /// </summary>
        public static unsafe NewReference GetCLRModule(BorrowedReference fromList = default)
        {
            root.InitializePreload();

            // update the module dictionary with the contents of the root dictionary
            root.LoadNames();
            BorrowedReference py_mod_dict = Runtime.PyModule_GetDict(ClrModuleReference);

            using (var clr_dict = Runtime.PyObject_GenericGetDict(root.ObjectReference))
            {
                Runtime.PyDict_Update(py_mod_dict, clr_dict);
            }

            // find any items from the from list and get them from the root if they're not
            // already in the module dictionary
            if (fromList != null)
            {
                if (Runtime.PyTuple_Check(fromList))
                {
                    using var mod_dict = new PyDict(py_mod_dict);
                    using var from     = new PyTuple(fromList);
                    foreach (PyObject item in from)
                    {
                        if (mod_dict.HasKey(item))
                        {
                            continue;
                        }

                        var s = item.AsManagedObject(typeof(string)) as string;
                        if (s == null)
                        {
                            continue;
                        }

                        ManagedType attr = root.GetAttribute(s, true);
                        if (attr == null)
                        {
                            continue;
                        }

                        Runtime.XIncref(attr.pyHandle);
                        using (var obj = new PyObject(attr.pyHandle))
                        {
                            mod_dict.SetItem(s, obj);
                        }
                    }
                }
            }
            Runtime.XIncref(py_clr_module);
            return(NewReference.DangerousFromPointer(py_clr_module));
        }
示例#11
0
        /// <summary>
        /// ImportAll Method
        /// </summary>
        /// <remarks>
        /// Import all variables of the module into this scope.
        /// </remarks>
        public void ImportAll(PyObject module)
        {
            if (Runtime.PyObject_Type(module.obj) != Runtime.PyModuleType)
            {
                throw new PyScopeException("object is not a module");
            }
            var module_dict = Runtime.PyModule_GetDict(module.obj);
            int result      = Runtime.PyDict_Update(variables, module_dict);

            if (result < 0)
            {
                throw new PythonException();
            }
        }
示例#12
0
        /// <summary>
        /// ImportAll Method
        /// </summary>
        /// <remarks>
        /// Import all variables of the module into this scope.
        /// </remarks>
        public void ImportAll(PyObject module)
        {
            if (Runtime.PyObject_Type(module.obj) != Runtime.PyModuleType)
            {
                throw new PyScopeException("object is not a module");
            }
            var module_dict = Runtime.PyModule_GetDict(module.Reference);
            int result      = Runtime.PyDict_Update(VarsRef, module_dict);

            if (result < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
        }
示例#13
0
        /// <summary>
        /// Initialization performed on startup of the Python runtime.
        /// </summary>
        internal static unsafe void Initialize()
        {
            // Initialize the clr module and tell Python about it.
            root = new CLRModule();

            // create a python module with the same methods as the clr module-like object
            py_clr_module = Runtime.PyModule_New("clr").DangerousMoveToPointer();

            // both dicts are borrowed references
            BorrowedReference mod_dict = Runtime.PyModule_GetDict(ClrModuleReference);

            using var clr_dict = Runtime.PyObject_GenericGetDict(root.ObjectReference);

            Runtime.PyDict_Update(mod_dict, clr_dict);
            BorrowedReference dict = Runtime.PyImport_GetModuleDict();

            Runtime.PyDict_SetItemString(dict, "CLR", ClrModuleReference);
            Runtime.PyDict_SetItemString(dict, "clr", ClrModuleReference);
            SetupNamespaceTracking();
            SetupImportHook();
        }
示例#14
0
        /// <summary>
        /// Initialization performed on startup of the Python runtime.
        /// </summary>
        internal static unsafe void Initialize()
        {
            InitImport();

            // Initialize the clr module and tell Python about it.
            root = new CLRModule();

            // 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
            BorrowedReference mod_dict = Runtime.PyModule_GetDict(ClrModuleReference);
            BorrowedReference clr_dict = *Runtime._PyObject_GetDictPtr(root.ObjectReference);

            Runtime.PyDict_Update(mod_dict, clr_dict);
            BorrowedReference dict = Runtime.PyImport_GetModuleDict();

            Runtime.PyDict_SetItemString(dict, "CLR", ClrModuleReference);
            Runtime.PyDict_SetItemString(dict, "clr", ClrModuleReference);
        }
示例#15
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
        }
示例#16
0
        internal static IntPtr CreateSubType(IntPtr py_name, IntPtr py_base_type, IntPtr py_dict)
        {
            // Utility to create a subtype of a managed type with the ability for the
            // a python subtype able to override the managed implementation
            string name = Runtime.GetManagedString(py_name);

            // the derived class can have class attributes __assembly__ and __module__ which
            // control the name of the assembly and module the new type is created in.
            object assembly     = null;
            object namespaceStr = null;

            var disposeList = new List <PyObject>();

            try
            {
                var assemblyKey = new PyObject(Converter.ToPython("__assembly__", typeof(string)));
                disposeList.Add(assemblyKey);
                if (0 != Runtime.PyMapping_HasKey(py_dict, assemblyKey.Handle))
                {
                    var pyAssembly = new PyObject(Runtime.PyDict_GetItem(py_dict, assemblyKey.Handle));
                    Runtime.XIncref(pyAssembly.Handle);
                    disposeList.Add(pyAssembly);
                    if (!Converter.ToManagedValue(pyAssembly.Handle, typeof(string), out assembly, false))
                    {
                        throw new InvalidCastException("Couldn't convert __assembly__ value to string");
                    }
                }

                var namespaceKey = new PyObject(Converter.ToPythonImplicit("__namespace__"));
                disposeList.Add(namespaceKey);
                if (0 != Runtime.PyMapping_HasKey(py_dict, namespaceKey.Handle))
                {
                    var pyNamespace = new PyObject(Runtime.PyDict_GetItem(py_dict, namespaceKey.Handle));
                    Runtime.XIncref(pyNamespace.Handle);
                    disposeList.Add(pyNamespace);
                    if (!Converter.ToManagedValue(pyNamespace.Handle, typeof(string), out namespaceStr, false))
                    {
                        throw new InvalidCastException("Couldn't convert __namespace__ value to string");
                    }
                }
            }
            finally
            {
                foreach (PyObject o in disposeList)
                {
                    o.Dispose();
                }
            }

            // create the new managed type subclassing the base managed type
            var baseClass = ManagedType.GetManagedObject(py_base_type) as ClassBase;

            if (null == baseClass)
            {
                return(Exceptions.RaiseTypeError("invalid base class, expected CLR class type"));
            }

            try
            {
                Type subType = ClassDerivedObject.CreateDerivedType(name,
                                                                    baseClass.type,
                                                                    py_dict,
                                                                    (string)namespaceStr,
                                                                    (string)assembly);

                // create the new ManagedType and python type
                ClassBase subClass = ClassManager.GetClass(subType);
                IntPtr    py_type  = GetTypeHandle(subClass, subType);

                // by default the class dict will have all the C# methods in it, but as this is a
                // derived class we want the python overrides in there instead if they exist.
                IntPtr cls_dict = Marshal.ReadIntPtr(py_type, TypeOffset.tp_dict);
                Runtime.PyDict_Update(cls_dict, py_dict);

                return(py_type);
            }
            catch (Exception e)
            {
                return(Exceptions.RaiseTypeError(e.Message));
            }
        }
示例#17
0
        internal static IntPtr CreateSubType(IntPtr py_name, IntPtr py_base_type, IntPtr py_dict)
        {
            var dictRef = new BorrowedReference(py_dict);
            // Utility to create a subtype of a managed type with the ability for the
            // a python subtype able to override the managed implementation
            string name = Runtime.GetManagedString(py_name);

            // the derived class can have class attributes __assembly__ and __module__ which
            // control the name of the assembly and module the new type is created in.
            object assembly     = null;
            object namespaceStr = null;

            using (var assemblyKey = new PyString("__assembly__"))
            {
                var assemblyPtr = Runtime.PyDict_GetItemWithError(dictRef, assemblyKey.Reference);
                if (assemblyPtr.IsNull)
                {
                    if (Exceptions.ErrorOccurred())
                    {
                        return(IntPtr.Zero);
                    }
                }
                else if (!Converter.ToManagedValue(assemblyPtr, typeof(string), out assembly, true))
                {
                    return(Exceptions.RaiseTypeError("Couldn't convert __assembly__ value to string"));
                }

                using (var namespaceKey = new PyString("__namespace__"))
                {
                    var pyNamespace = Runtime.PyDict_GetItemWithError(dictRef, namespaceKey.Reference);
                    if (pyNamespace.IsNull)
                    {
                        if (Exceptions.ErrorOccurred())
                        {
                            return(IntPtr.Zero);
                        }
                    }
                    else if (!Converter.ToManagedValue(pyNamespace, typeof(string), out namespaceStr, true))
                    {
                        return(Exceptions.RaiseTypeError("Couldn't convert __namespace__ value to string"));
                    }
                }
            }

            // create the new managed type subclassing the base managed type
            var baseClass = ManagedType.GetManagedObject(py_base_type) as ClassBase;

            if (null == baseClass)
            {
                return(Exceptions.RaiseTypeError("invalid base class, expected CLR class type"));
            }

            try
            {
                Type subType = ClassDerivedObject.CreateDerivedType(name,
                                                                    baseClass.type.Value,
                                                                    py_dict,
                                                                    (string)namespaceStr,
                                                                    (string)assembly);

                // create the new ManagedType and python type
                ClassBase subClass = ClassManager.GetClass(subType);
                IntPtr    py_type  = GetTypeHandle(subClass, subType);

                // by default the class dict will have all the C# methods in it, but as this is a
                // derived class we want the python overrides in there instead if they exist.
                var cls_dict = new BorrowedReference(Marshal.ReadIntPtr(py_type, TypeOffset.tp_dict));
                ThrowIfIsNotZero(Runtime.PyDict_Update(cls_dict, new BorrowedReference(py_dict)));
                Runtime.XIncref(py_type);
                // Update the __classcell__ if it exists
                BorrowedReference cell = Runtime.PyDict_GetItemString(cls_dict, "__classcell__");
                if (!cell.IsNull)
                {
                    ThrowIfIsNotZero(Runtime.PyCell_Set(cell, py_type));
                    ThrowIfIsNotZero(Runtime.PyDict_DelItemString(cls_dict, "__classcell__"));
                }

                return(py_type);
            }
            catch (Exception e)
            {
                return(Exceptions.RaiseTypeError(e.Message));
            }
        }