Exemple #1
0
        /// <summary>
        /// AsLong Method
        /// </summary>
        /// <remarks>
        /// Convert a Python object to a Python long if possible, raising
        /// a PythonException if the conversion is not possible. This is
        /// equivalent to the Python expression "long(object)".
        /// </remarks>
        public static PyLong AsLong(PyObject value)
        {
            IntPtr op = Runtime.PyNumber_Long(value.obj);

            PythonException.ThrowIfIsNull(op);
            return(new PyLong(op));
        }
Exemple #2
0
 private void Exec(string code, BorrowedReference _globals, BorrowedReference _locals)
 {
     using NewReference reference = Runtime.PyRun_String(
               code, RunFlagType.File, _globals, _locals
               );
     PythonException.ThrowIfIsNull(reference);
 }
Exemple #3
0
        private static IntPtr FromLong(long value)
        {
            IntPtr val = Runtime.PyInt_FromInt64(value);

            PythonException.ThrowIfIsNull(val);
            return(val);
        }
Exemple #4
0
        static void SetupImportHook()
        {
            // Create the import hook module
            using var import_hook_module = Runtime.PyModule_New("clr.loader");
            BorrowedReference mod_dict = Runtime.PyModule_GetDict(import_hook_module.BorrowOrThrow());

            Debug.Assert(mod_dict != null);

            // Run the python code to create the module's classes.
            var builtins = Runtime.PyEval_GetBuiltins();
            var exec     = Runtime.PyDict_GetItemString(builtins, "exec");

            using var args = Runtime.PyTuple_New(2);
            PythonException.ThrowIfIsNull(args);
            using var codeStr = Runtime.PyString_FromString(LoaderCode);
            Runtime.PyTuple_SetItem(args.Borrow(), 0, codeStr.StealOrThrow());

            // reference not stolen due to overload incref'ing for us.
            Runtime.PyTuple_SetItem(args.Borrow(), 1, mod_dict);
            Runtime.PyObject_Call(exec, args.Borrow(), default).Dispose();
            // Set as a sub-module of clr.
            if (Runtime.PyModule_AddObject(ClrModuleReference, "loader", import_hook_module.Steal()) != 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }

            // Finally, add the hook to the meta path
            var findercls = Runtime.PyDict_GetItemString(mod_dict, "DotNetFinder");

            using var finderCtorArgs = Runtime.PyTuple_New(0);
            using var finder_inst    = Runtime.PyObject_CallObject(findercls, finderCtorArgs.Borrow());
            var metapath = Runtime.PySys_GetObject("meta_path");

            PythonException.ThrowIfIsNotZero(Runtime.PyList_Append(metapath, finder_inst.BorrowOrThrow()));
        }
Exemple #5
0
        private static IntPtr FromString(string s)
        {
            IntPtr val = Runtime.PyUnicode_FromUnicode(s, s.Length);

            PythonException.ThrowIfIsNull(val);
            return(val);
        }
Exemple #6
0
        /// <summary>
        /// Reloads the module, and returns the updated object
        /// </summary>
        public PyModule Reload()
        {
            NewReference op = Runtime.PyImport_ReloadModule(this.Reference);

            PythonException.ThrowIfIsNull(op);
            return(new PyModule(ref op));
        }
Exemple #7
0
        /// <summary>
        /// AsTuple Method
        /// </summary>
        /// <remarks>
        /// Convert a Python object to a Python tuple if possible, raising
        /// a PythonException if the conversion is not possible. This is
        /// equivalent to the Python expression "tuple(object)".
        /// </remarks>
        public static PyTuple AsTuple(PyObject value)
        {
            IntPtr op = Runtime.PySequence_Tuple(value.obj);

            PythonException.ThrowIfIsNull(op);
            return(new PyTuple(op));
        }
Exemple #8
0
        /// <summary>
        /// Given a module or package name, import the
        /// module and return the resulting module object as a <see cref="PyModule"/>.
        /// </summary>
        /// <param name="name">Fully-qualified module or package name</param>
        public static PyModule Import(string name)
        {
            NewReference op = Runtime.PyImport_ImportModule(name);

            PythonException.ThrowIfIsNull(op);
            return(new PyModule(ref op));
        }
Exemple #9
0
        /// <summary>
        /// ReloadModule Method
        /// </summary>
        /// <remarks>
        /// Given a PyObject representing a previously loaded module, reload
        /// the module.
        /// </remarks>
        public static PyObject ReloadModule(PyObject module)
        {
            IntPtr op = Runtime.PyImport_ReloadModule(module.Handle);

            PythonException.ThrowIfIsNull(op);
            return(new PyObject(op));
        }
Exemple #10
0
        private static IntPtr FromInt(int value)
        {
            IntPtr val = Runtime.PyLong_FromLong(value);

            PythonException.ThrowIfIsNull(val);
            return(val);
        }
Exemple #11
0
        /// <summary>
        /// Utility method to allocate a type object &amp; do basic initialization.
        /// </summary>
        internal static IntPtr AllocateTypeObject(string name, IntPtr metatype)
        {
            IntPtr type = Runtime.PyType_GenericAlloc(metatype, 0);

            PythonException.ThrowIfIsNull(type);
            // Clr type would not use __slots__,
            // and the PyMemberDef after PyHeapTypeObject will have other uses(e.g. type handle),
            // thus set the ob_size to 0 for avoiding slots iterations.
            Marshal.WriteIntPtr(type, TypeOffset.ob_size, IntPtr.Zero);

            // Cheat a little: we'll set tp_name to the internal char * of
            // the Python version of the type name - otherwise we'd have to
            // allocate the tp_name and would have no way to free it.
            IntPtr temp = Runtime.PyUnicode_FromString(name);
            IntPtr raw  = Runtime.PyUnicode_AsUTF8(temp);

            Marshal.WriteIntPtr(type, TypeOffset.tp_name, raw);
            Marshal.WriteIntPtr(type, TypeOffset.name, temp);

            Runtime.XIncref(temp);
            Marshal.WriteIntPtr(type, TypeOffset.qualname, temp);
            temp = type + TypeOffset.nb_add;
            Marshal.WriteIntPtr(type, TypeOffset.tp_as_number, temp);

            temp = type + TypeOffset.sq_length;
            Marshal.WriteIntPtr(type, TypeOffset.tp_as_sequence, temp);

            temp = type + TypeOffset.mp_length;
            Marshal.WriteIntPtr(type, TypeOffset.tp_as_mapping, temp);

            temp = type + TypeOffset.bf_getbuffer;
            Marshal.WriteIntPtr(type, TypeOffset.tp_as_buffer, temp);
            return(type);
        }
Exemple #12
0
        /// <summary>
        /// ImportModule Method
        /// </summary>
        /// <remarks>
        /// Given a fully-qualified module or package name, import the
        /// module and return the resulting module object as a PyObject
        /// or null if an exception is raised.
        /// </remarks>
        public static PyObject ImportModule(string name)
        {
            IntPtr op = Runtime.PyImport_ImportModule(name);

            PythonException.ThrowIfIsNull(op);
            return(new PyObject(op));
        }
Exemple #13
0
        internal static IntPtr FromLong(long value)
        {
            IntPtr val = Runtime.PyLong_FromLongLong(value);

            PythonException.ThrowIfIsNull(val);
            return(val);
        }
Exemple #14
0
        private static IntPtr FromULong(ulong value)
        {
            IntPtr val = Runtime.PyLong_FromUnsignedLongLong(value);

            PythonException.ThrowIfIsNull(val);
            return(val);
        }
Exemple #15
0
        private static IntPtr FromString(string s)
        {
            IntPtr val = Runtime.PyString_FromString(s);

            PythonException.ThrowIfIsNull(val);
            return(val);
        }
Exemple #16
0
        private static IntPtr FromString(string value)
        {
            IntPtr val = Runtime.PyLong_FromString(value, IntPtr.Zero, 0);

            PythonException.ThrowIfIsNull(val);
            return(val);
        }
Exemple #17
0
        private static IntPtr FromDouble(double value)
        {
            IntPtr val = Runtime.PyLong_FromDouble(value);

            PythonException.ThrowIfIsNull(val);
            return(val);
        }
Exemple #18
0
        /// <summary>
        /// AsFloat Method
        /// </summary>
        /// <remarks>
        /// Convert a Python object to a Python float if possible, raising
        /// a PythonException if the conversion is not possible. This is
        /// equivalent to the Python expression "float(object)".
        /// </remarks>
        public static PyFloat AsFloat(PyObject value)
        {
            IntPtr op = Runtime.PyNumber_Float(value.obj);

            PythonException.ThrowIfIsNull(op);
            return(new PyFloat(op));
        }
Exemple #19
0
 /// <summary>
 /// PyFloat Constructor
 /// </summary>
 /// <remarks>
 /// Creates a new Python float from a string value.
 /// </remarks>
 public PyFloat(string value)
 {
     using (var s = new PyString(value))
     {
         obj = Runtime.PyFloat_FromString(s.obj, IntPtr.Zero);
         PythonException.ThrowIfIsNull(obj);
     }
 }
Exemple #20
0
        public static PyObject Compile(string code, string filename = "", RunFlagType mode = RunFlagType.File)
        {
            var    flag = (int)mode;
            IntPtr ptr  = Runtime.Py_CompileString(code, filename, flag);

            PythonException.ThrowIfIsNull(ptr);
            return(new PyObject(ptr));
        }
Exemple #21
0
 private static IntPtr FromString(string value)
 {
     using (var s = new PyString(value))
     {
         NewReference val = Runtime.PyFloat_FromString(s.Reference);
         PythonException.ThrowIfIsNull(val);
         return(val.DangerousMoveToPointerOrNull());
     }
 }
Exemple #22
0
        private void Exec(string code, IntPtr _globals, IntPtr _locals)
        {
            NewReference reference = Runtime.PyRun_String(
                code, RunFlagType.File, _globals, _locals
                );

            PythonException.ThrowIfIsNull(reference);
            reference.Dispose();
        }
Exemple #23
0
        public static PyModule FromString(string name, string code)
        {
            using NewReference c = Runtime.Py_CompileString(code, "none", (int)RunFlagType.File);
            PythonException.ThrowIfIsNull(c);
            NewReference m = Runtime.PyImport_ExecCodeModule(name, c);

            PythonException.ThrowIfIsNull(m);
            return(new PyModule(ref m));
        }
Exemple #24
0
 private static IntPtr FromString(string value)
 {
     using (var s = new PyString(value))
     {
         IntPtr val = Runtime.PyFloat_FromString(s.obj, IntPtr.Zero);
         PythonException.ThrowIfIsNull(val);
         return(val);
     }
 }
Exemple #25
0
        private void Exec(string code, IntPtr _globals, IntPtr _locals)
        {
            var          flag      = (IntPtr)Runtime.Py_file_input;
            NewReference reference = Runtime.PyRun_String(
                code, flag, _globals, _locals
                );

            PythonException.ThrowIfIsNull(reference);
            reference.Dispose();
        }
Exemple #26
0
        /// <summary>
        /// ModuleFromString Method
        /// </summary>
        /// <remarks>
        /// Given a string module name and a string containing Python code,
        /// execute the code in and return a module of the given name.
        /// </remarks>
        public static PyObject ModuleFromString(string name, string code)
        {
            IntPtr c = Runtime.Py_CompileString(code, "none", (int)RunFlagType.File);

            PythonException.ThrowIfIsNull(c);
            IntPtr m = Runtime.PyImport_ExecCodeModule(name, c);

            PythonException.ThrowIfIsNull(m);
            return(new PyObject(m));
        }
Exemple #27
0
        static NewReference CreateMultidimensional(Type elementType, long[] dimensions, BorrowedReference shapeTuple, BorrowedReference pyType)
        {
            for (int dimIndex = 0; dimIndex < dimensions.Length; dimIndex++)
            {
                BorrowedReference dimObj = Runtime.PyTuple_GetItem(shapeTuple, dimIndex);
                PythonException.ThrowIfIsNull(dimObj);

                if (!Runtime.PyInt_Check(dimObj))
                {
                    Exceptions.RaiseTypeError("array constructor expects integer dimensions");
                    return(default);
Exemple #28
0
        /// <summary>
        /// PyIter factory function.
        /// </summary>
        /// <remarks>
        /// Create a new PyIter from a given iterable.  Like doing "iter(iterable)" in python.
        /// </remarks>
        /// <param name="iterable"></param>
        /// <returns></returns>
        public static PyIter GetIter(PyObject iterable)
        {
            if (iterable == null)
            {
                throw new ArgumentNullException();
            }
            IntPtr val = Runtime.PyObject_GetIter(iterable.obj);

            PythonException.ThrowIfIsNull(val);
            return(new PyIter(val));
        }
Exemple #29
0
        /// <summary>
        /// Eval method
        /// </summary>
        /// <remarks>
        /// Evaluate a Python expression and return the result as a PyObject
        /// or null if an exception is raised.
        /// </remarks>
        public PyObject Eval(string code, PyDict locals = null)
        {
            Check();
            IntPtr _locals = locals == null ? variables : locals.obj;

            NewReference reference = Runtime.PyRun_String(
                code, RunFlagType.Eval, variables, _locals
                );

            PythonException.ThrowIfIsNull(reference);
            return(reference.MoveToPyObject());
        }
Exemple #30
0
        /// <summary>
        /// Eval method
        /// </summary>
        /// <remarks>
        /// Evaluate a Python expression and return the result as a PyObject
        /// or null if an exception is raised.
        /// </remarks>
        public PyObject Eval(string code, PyDict locals = null)
        {
            Check();
            BorrowedReference _locals = locals == null ? VarsRef : locals.Reference;

            NewReference reference = Runtime.PyRun_String(
                code, RunFlagType.Eval, VarsRef, _locals
                );

            PythonException.ThrowIfIsNull(reference);
            return(reference.MoveToPyObject());
        }