Dispose() public method

public Dispose ( ) : void
return void
示例#1
0
 protected override void Dispose(bool disposing)
 {
     if (null != _current)
     {
         _current.Dispose();
         _current = null;
     }
     base.Dispose(disposing);
 }
        static Converter.TryConvertFromPythonDelegate GetDecoder(IntPtr sourceType, Type targetType)
        {
            IPyObjectDecoder decoder;

            using (var pyType = new PyObject(Runtime.SelfIncRef(sourceType)))
            {
                lock (decoders)
                {
                    decoder = decoders.GetDecoder(pyType, targetType);
                    if (decoder == null)
                    {
                        return(null);
                    }
                }
            }

            var decode = genericDecode.MakeGenericMethod(targetType);

            bool TryDecode(IntPtr pyHandle, out object result)
            {
                var  pyObj   = new PyObject(Runtime.SelfIncRef(pyHandle));
                var  @params = new object[] { pyObj, null };
                bool success = (bool)decode.Invoke(decoder, @params);

                if (!success)
                {
                    pyObj.Dispose();
                }

                result = @params[1];
                return(success);
            }

            return(TryDecode);
        }
示例#3
0
        /// <summary>
        /// InvokeMethod Method
        /// </summary>
        /// <remarks>
        /// Invoke the named method of the object with the given arguments
        /// and keyword arguments. Keyword args are passed as a PyDict object.
        /// A PythonException is raised if the invokation is unsuccessful.
        /// </remarks>
        public PyObject InvokeMethod(string name, PyTuple args, PyDict kw)
        {
            PyObject method = GetAttr(name);
            PyObject result = method.Invoke(args, kw);

            method.Dispose();
            return(result);
        }
示例#4
0
        /// <summary>
        /// InvokeMethod Method
        /// </summary>
        /// <remarks>
        /// Invoke the named method of the object with the given arguments.
        /// A PythonException is raised if the invokation is unsuccessful.
        /// </remarks>
        public PyObject InvokeMethod(string name, params PyObject[] args)
        {
            PyObject method = GetAttr(name);
            PyObject result = method.Invoke(args);

            method.Dispose();
            return(result);
        }
示例#5
0
 public static void Shutdown()
 {
     if (_opType != null)
     {
         _opType.Dispose();
         _opType = null;
     }
 }
示例#6
0
        /// <summary>
        /// Exec Method
        /// </summary>
        /// <remarks>
        /// Run a string containing Python code.
        /// It's a subset of Python exec function.
        /// </remarks>
        public static void Exec(string code, IntPtr?globals = null, IntPtr?locals = null)
        {
            PyObject result = RunString(code, globals, locals, RunFlagType.File);

            if (result.obj != Runtime.PyNone)
            {
                throw new PythonException();
            }
            result.Dispose();
        }
示例#7
0
        public static void InitExt()
        {
#endif
            try
            {
                Initialize();

                // Trickery - when the import hook is installed into an already
                // running Python, the standard import machinery is still in
                // control for the duration of the import that caused bootstrap.
                //
                // That is problematic because the std machinery tries to get
                // sub-names directly from the module __dict__ rather than going
                // through our module object's getattr hook. This workaround is
                // evil ;) We essentially climb up the stack looking for the
                // import that caused the bootstrap to happen, then re-execute
                // the import explicitly after our hook has been installed. By
                // doing this, the original outer import should work correctly.
                //
                // Note that this is only needed during the execution of the
                // first import that installs the CLR import hook. This hack
                // still doesn't work if you use the interactive interpreter,
                // since there is no line info to get the import line ;(

                string code =

                    "import traceback\n" +
                    "for item in traceback.extract_stack():\n" +
                    "    line = item[3]\n" +
                    "    if line is not None:\n" +
                    "        if line.startswith('import CLR') or \\\n" +
                    "           line.startswith('import clr') or \\\n" +
                    "           line.startswith('from clr') or \\\n" +
                    "           line.startswith('from CLR'):\n" +
                    "            exec(line)\n" +
                    "            break\n";

                PyObject r = PythonEngine.RunString(code);
                if (r != null)
                {
                    r.Dispose();
                }
            }
            catch (PythonException e)
            {
                e.Restore();
#if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35)
                return(IntPtr.Zero);
#endif
            }

#if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35)
            return(Python.Runtime.ImportHook.GetCLRModule());
#endif
        }
示例#8
0
        /// <summary>
        /// Cleanup resources upon shutdown of the Python runtime.
        /// </summary>
        internal static void Shutdown()
        {
            if (Runtime.Py_IsInitialized() == 0)
            {
                return;
            }

            TeardownNameSpaceTracking();
            clrModule.ResetModuleMembers();
            Runtime.Py_CLEAR(ref py_clr_module !);

            root.Dispose();
            root = null !;
        }
示例#9
0
        /// <summary>
        /// InvokeMethod Method
        /// </summary>
        /// <remarks>
        /// Invoke the named method of the object with the given arguments
        /// and keyword arguments. Keyword args are passed as a PyDict object.
        /// A PythonException is raised if the invocation is unsuccessful.
        /// </remarks>
        public PyObject InvokeMethod(string name, PyTuple args, PyDict kw)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            PyObject method = GetAttr(name);
            PyObject result = method.Invoke(args, kw);

            method.Dispose();
            return(result);
        }
示例#10
0
 /// <summary>
 /// Cleanup resources upon shutdown of the Python runtime.
 /// </summary>
 internal static void Shutdown()
 {
     if (Runtime.Py_IsInitialized() == 0)
     {
         return;
     }
     Type type = typeof(Exceptions);
     foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static))
     {
         var op = (PyObject?)fi.GetValue(type);
         if (op is null)
         {
             continue;
         }
         op.Dispose();
         fi.SetValue(null, null);
     }
     exceptions_module.Dispose();
     warnings_module.Dispose();
 }
示例#11
0
        /// <summary>
        /// InvokeMethod Method
        /// </summary>
        /// <remarks>
        /// Invoke the named method of the object with the given arguments.
        /// A PythonException is raised if the invocation is unsuccessful.
        /// </remarks>
        public PyObject InvokeMethod(PyObject name, params PyObject[] args)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }
            if (args.Contains(null))
            {
                throw new ArgumentNullException();
            }

            PyObject method = GetAttr(name);
            PyObject result = method.Invoke(args);

            method.Dispose();
            return(result);
        }
示例#12
0
        /// <summary>
        /// Cleanup resources upon shutdown of the Python runtime.
        /// </summary>
        internal static void Shutdown()
        {
            if (Runtime.Py_IsInitialized() == 0)
            {
                return;
            }
            Type type = typeof(Exceptions);

            foreach (FieldInfo fi in type.GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                var op = (IntPtr)fi.GetValue(type);
                if (op == IntPtr.Zero)
                {
                    continue;
                }
                Runtime.XDecref(op);
                fi.SetValue(null, IntPtr.Zero);
            }
            exceptions_module.Dispose();
            warnings_module.Dispose();
        }
示例#13
0
        /// <summary>
        /// Initialize Method
        /// </summary>
        /// <remarks>
        /// Initialize the Python runtime. It is safe to call this method
        /// more than once, though initialization will only happen on the
        /// first call. It is *not* necessary to hold the Python global
        /// interpreter lock (GIL) to call this method.
        /// initSigs can be set to 1 to do default python signal configuration. This will override the way signals are handled by the application.
        /// </remarks>
        public static void Initialize(IEnumerable <string> args, bool setSysArgv = true, bool initSigs = false)
        {
            if (!initialized)
            {
                // Creating the delegateManager MUST happen before Runtime.Initialize
                // is called. If it happens afterwards, DelegateManager's CodeGenerator
                // throws an exception in its ctor.  This exception is eaten somehow
                // during an initial "import clr", and the world ends shortly thereafter.
                // This is probably masking some bad mojo happening somewhere in Runtime.Initialize().
                delegateManager = new DelegateManager();
                Runtime.Initialize(initSigs);
                initialized = true;
                Exceptions.Clear();

                // Make sure we clean up properly on app domain unload.
                AppDomain.CurrentDomain.DomainUnload += OnDomainUnload;

                // Remember to shut down the runtime.
                AddShutdownHandler(Runtime.Shutdown);

                // The global scope gets used implicitly quite early on, remember
                // to clear it out when we shut down.
                AddShutdownHandler(PyScopeManager.Global.Clear);

                if (setSysArgv)
                {
                    Py.SetArgv(args);
                }

                // register the atexit callback (this doesn't use Py_AtExit as the C atexit
                // callbacks are called after python is fully finalized but the python ones
                // are called while the python engine is still running).
                string code =
                    "import atexit, clr\n" +
                    "atexit.register(clr._AtExit)\n";
                PythonEngine.Exec(code);

                // Load the clr.py resource into the clr module
                IntPtr clr      = Python.Runtime.ImportHook.GetCLRModule();
                IntPtr clr_dict = Runtime.PyModule_GetDict(clr);

                var locals = new PyDict();
                try
                {
                    IntPtr module         = Runtime.PyImport_AddModule("clr._extras");
                    IntPtr module_globals = Runtime.PyModule_GetDict(module);
                    IntPtr builtins       = Runtime.PyEval_GetBuiltins();
                    Runtime.PyDict_SetItemString(module_globals, "__builtins__", builtins);

                    Assembly assembly = Assembly.GetExecutingAssembly();
                    using (Stream stream = assembly.GetManifestResourceStream("clr.py"))
                        using (var reader = new StreamReader(stream))
                        {
                            // add the contents of clr.py to the module
                            string clr_py = reader.ReadToEnd();
                            Exec(clr_py, module_globals, locals.Handle);
                        }

                    // add the imported module to the clr module, and copy the API functions
                    // and decorators into the main clr module.
                    Runtime.PyDict_SetItemString(clr_dict, "_extras", module);
                    foreach (PyObject key in locals.Keys())
                    {
                        if (!key.ToString().StartsWith("_") || key.ToString().Equals("__version__"))
                        {
                            PyObject value = locals[key];
                            Runtime.PyDict_SetItem(clr_dict, key.Handle, value.Handle);
                            value.Dispose();
                        }
                        key.Dispose();
                    }
                }
                finally
                {
                    locals.Dispose();
                }
            }
        }
示例#14
0
        /// <summary>
        /// Initialize Method
        /// </summary>
        ///
        /// <remarks>
        /// Initialize the Python runtime. It is safe to call this method
        /// more than once, though initialization will only happen on the
        /// first call. It is *not* necessary to hold the Python global
        /// interpreter lock (GIL) to call this method.
        /// </remarks>
        public static void Initialize()
        {
            if (!initialized)
            {
                // Creating the delegateManager MUST happen before Runtime.Initialize
                // is called. If it happens afterwards, DelegateManager's CodeGenerator
                // throws an exception in its ctor.  This exception is eaten somehow
                // during an initial "import clr", and the world ends shortly thereafter.
                // This is probably masking some bad mojo happening somewhere in Runtime.Initialize().
                delegateManager = new DelegateManager();
                Runtime.Initialize();
                initialized = true;
                Exceptions.Clear();

                // register the atexit callback (this doesn't use Py_AtExit as the C atexit
                // callbacks are called after python is fully finalized but the python ones
                // are called while the python engine is still running).
                string code =
                    "import atexit, clr\n" +
                    "atexit.register(clr._AtExit)\n";
                PyObject r = PythonEngine.RunString(code);
                if (r != null)
                {
                    r.Dispose();
                }

                // Load the clr.py resource into the clr module
                IntPtr clr      = Python.Runtime.ImportHook.GetCLRModule();
                IntPtr clr_dict = Runtime.PyModule_GetDict(clr);

                PyDict locals = new PyDict();
                try
                {
                    IntPtr module         = Runtime.PyImport_AddModule("clr._extras");
                    IntPtr module_globals = Runtime.PyModule_GetDict(module);
                    IntPtr builtins       = Runtime.PyEval_GetBuiltins();
                    Runtime.PyDict_SetItemString(module_globals, "__builtins__", builtins);

                    var assembly = Assembly.GetExecutingAssembly();
                    using (Stream stream = assembly.GetManifestResourceStream("clr.py"))
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            // add the contents of clr.py to the module
                            string   clr_py = reader.ReadToEnd();
                            PyObject result = RunString(clr_py, module_globals, locals.Handle);
                            if (null == result)
                            {
                                throw new PythonException();
                            }
                            result.Dispose();
                        }

                    // add the imported module to the clr module, and copy the API functions
                    // and decorators into the main clr module.
                    Runtime.PyDict_SetItemString(clr_dict, "_extras", module);
                    foreach (PyObject key in locals.Keys())
                    {
                        if (!key.ToString().StartsWith("_"))
                        {
                            PyObject value = locals[key];
                            Runtime.PyDict_SetItem(clr_dict, key.Handle, value.Handle);
                            value.Dispose();
                        }
                        key.Dispose();
                    }
                }
                finally
                {
                    locals.Dispose();
                }
            }
        }