Ejemplo n.º 1
0
        unsafe internal PyBuffer(PyObject exporter, PyBUF flags)
        {
            _view = new Py_buffer();

            if (Runtime.PyObject_GetBuffer(exporter.Handle, ref _view, (int)flags) < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }

            _exporter = exporter;

            var intPtrBuf = new IntPtr[_view.ndim];

            if (_view.shape != IntPtr.Zero)
            {
                Marshal.Copy(_view.shape, intPtrBuf, 0, (int)_view.len * sizeof(IntPtr));
                Shape = intPtrBuf.Select(x => (long)x).ToArray();
            }

            if (_view.strides != IntPtr.Zero)
            {
                Marshal.Copy(_view.strides, intPtrBuf, 0, (int)_view.len * sizeof(IntPtr));
                Strides = intPtrBuf.Select(x => (long)x).ToArray();
            }

            if (_view.suboffsets != IntPtr.Zero)
            {
                Marshal.Copy(_view.suboffsets, intPtrBuf, 0, (int)_view.len * sizeof(IntPtr));
                SubOffsets = intPtrBuf.Select(x => (long)x).ToArray();
            }
        }
Ejemplo n.º 2
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()));
        }
Ejemplo n.º 3
0
        static void SetupImportHook()
        {
            // Create the import hook module
            var import_hook_module = Runtime.PyModule_New("clr.loader");

            // 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 = NewReference.DangerousFromPointer(Runtime.PyTuple_New(2));

            var codeStr = NewReference.DangerousFromPointer(Runtime.PyString_FromString(LoaderCode));

            Runtime.PyTuple_SetItem(args, 0, codeStr);
            var mod_dict = Runtime.PyModule_GetDict(import_hook_module);

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

            // Finally, add the hook to the meta path
            var findercls      = Runtime.PyDict_GetItemString(mod_dict, "DotNetFinder");
            var finderCtorArgs = NewReference.DangerousFromPointer(Runtime.PyTuple_New(0));
            var finder_inst    = Runtime.PyObject_CallObject(findercls, finderCtorArgs);
            var metapath       = Runtime.PySys_GetObject("meta_path");

            Runtime.PyList_Append(metapath, finder_inst);
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Shortcut for (pointer == NULL) -&gt; throw PythonException
 /// </summary>
 /// <param name="pointer">Pointer to a Python object</param>
 internal static void ErrorCheck(BorrowedReference pointer)
 {
     if (pointer.IsNull)
     {
         throw PythonException.ThrowLastAsClrException();
     }
 }
Ejemplo n.º 5
0
        /// <summary>
        /// Set the 'args' slot on a python exception object that wraps
        /// a CLR exception. This is needed for pickling CLR exceptions as
        /// BaseException_reduce will only check the slots, bypassing the
        /// __getattr__ implementation, and thus dereferencing a NULL
        /// pointer.
        /// </summary>
        internal static void SetArgsAndCause(BorrowedReference ob, Exception e)
        {
            IntPtr args;

            if (!string.IsNullOrEmpty(e.Message))
            {
                args = Runtime.PyTuple_New(1);
                IntPtr msg = Runtime.PyString_FromString(e.Message);
                Runtime.PyTuple_SetItem(args, 0, msg);
            }
            else
            {
                args = Runtime.PyTuple_New(0);
            }

            using var argsTuple = NewReference.DangerousFromPointer(args);

            if (Runtime.PyObject_SetAttrString(ob, "args", argsTuple) != 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }

            if (e.InnerException != null)
            {
                // Note: For an AggregateException, InnerException is only the first of the InnerExceptions.
                using var cause = CLRObject.GetReference(e.InnerException);
                Runtime.PyException_SetCause(ob, cause.Steal());
            }
        }
Ejemplo n.º 6
0
        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 PythonException.ThrowLastAsClrException();
                }
                pair.Value.DecrRefCount();
            }

            cache.Clear();
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Shortcut for (pointer == NULL or ErrorOccurred()) -&gt; throw PythonException
 /// </summary>
 internal static void ErrorOccurredCheck(IntPtr pointer)
 {
     if (pointer == IntPtr.Zero || ErrorOccurred())
     {
         throw PythonException.ThrowLastAsClrException();
     }
 }
Ejemplo n.º 8
0
 /// <summary>
 /// PyList Constructor
 /// </summary>
 /// <remarks>
 /// Creates a new empty Python list object.
 /// </remarks>
 public PyList() : base(Runtime.PyList_New(0))
 {
     if (obj == IntPtr.Zero)
     {
         throw PythonException.ThrowLastAsClrException();
     }
 }
Ejemplo n.º 9
0
 /// <summary>
 /// TryGet Method
 /// </summary>
 /// <remarks>
 /// Returns the value of the variable, local variable first.
 /// If the variable does not exist, return null.
 /// </remarks>
 public bool TryGet(string name, out PyObject value)
 {
     Check();
     using (var pyKey = new PyString(name))
     {
         if (Runtime.PyMapping_HasKey(variables, pyKey.obj) != 0)
         {
             IntPtr op = Runtime.PyObject_GetItem(variables, pyKey.obj);
             if (op == IntPtr.Zero)
             {
                 throw PythonException.ThrowLastAsClrException();
             }
             if (op == Runtime.PyNone)
             {
                 Runtime.XDecref(op);
                 value = null;
                 return(true);
             }
             value = new PyObject(op);
             return(true);
         }
         else
         {
             value = null;
             return(false);
         }
     }
 }
Ejemplo n.º 10
0
 internal static IntPtr ErrorCheckIfNull(IntPtr pointer)
 {
     if (pointer == IntPtr.Zero && ErrorOccurred())
     {
         throw PythonException.ThrowLastAsClrException();
     }
     return(pointer);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// SetSlice Method
        /// </summary>
        /// <remarks>
        /// Sets the slice of the sequence with the given indices.
        /// </remarks>
        public void SetSlice(int i1, int i2, PyObject v)
        {
            int r = Runtime.PySequence_SetSlice(obj, i1, i2, v.obj);

            if (r < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Sort Method
        /// </summary>
        /// <remarks>
        /// Sort the list in place.
        /// </remarks>
        public void Sort()
        {
            int r = Runtime.PyList_Sort(this.Reference);

            if (r < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Insert Method
        /// </summary>
        /// <remarks>
        /// Insert an item in the list object at the given index.
        /// </remarks>
        public void Insert(int index, PyObject item)
        {
            int r = Runtime.PyList_Insert(this.Reference, index, item.obj);

            if (r < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Append Method
        /// </summary>
        /// <remarks>
        /// Append an item to the list object.
        /// </remarks>
        public void Append(PyObject item)
        {
            int r = Runtime.PyList_Append(this.Reference, new BorrowedReference(item.obj));

            if (r < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// DelSlice Method
        /// </summary>
        /// <remarks>
        /// Deletes the slice of the sequence with the given indices.
        /// </remarks>
        public void DelSlice(int i1, int i2)
        {
            int r = Runtime.PySequence_DelSlice(obj, i1, i2);

            if (r < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Stores an attribute in the instance dict for future lookups.
 /// </summary>
 private void StoreAttribute(string name, ManagedType ob)
 {
     if (Runtime.PyDict_SetItemString(dict, name, ob.pyHandle) != 0)
     {
         throw PythonException.ThrowLastAsClrException();
     }
     ob.IncrRefCount();
     cache[name] = ob;
 }
Ejemplo n.º 17
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 PythonException.ThrowLastAsClrException();
            }
        }
Ejemplo n.º 18
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 PythonException.ThrowLastAsClrException();
            }
        }
Ejemplo n.º 19
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();
            }
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Keys Method
 /// </summary>
 /// <remarks>
 /// Returns a sequence containing the keys of the dictionary.
 /// </remarks>
 public PyObject Keys()
 {
     using var items = Runtime.PyDict_Keys(Reference);
     if (items.IsNull())
     {
         throw PythonException.ThrowLastAsClrException();
     }
     return(items.MoveToPyObject());
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Concat Method
        /// </summary>
        /// <remarks>
        /// Return the concatenation of the sequence object with the passed in
        /// sequence object.
        /// </remarks>
        public PyObject Concat(PyObject other)
        {
            IntPtr op = Runtime.PySequence_Concat(obj, other.obj);

            if (op == IntPtr.Zero)
            {
                throw PythonException.ThrowLastAsClrException();
            }
            return(new PyObject(op));
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Copy Method
        /// </summary>
        /// <remarks>
        /// Returns a copy of the dictionary.
        /// </remarks>
        public PyDict Copy()
        {
            IntPtr op = Runtime.PyDict_Copy(obj);

            if (op == IntPtr.Zero)
            {
                throw PythonException.ThrowLastAsClrException();
            }
            return(new PyDict(op));
        }
Ejemplo n.º 23
0
        internal static int ToInt32(BorrowedReference value)
        {
            nint num = Runtime.PyLong_AsSignedSize_t(value);

            if (num == -1 && Exceptions.ErrorOccurred())
            {
                throw PythonException.ThrowLastAsClrException();
            }
            return(checked ((int)num));
        }
Ejemplo n.º 24
0
        /// <summary>
        /// AsList Method
        /// </summary>
        /// <remarks>
        /// Converts a Python object to a Python list if possible, raising
        /// a PythonException if the conversion is not possible. This is
        /// equivalent to the Python expression "list(object)".
        /// </remarks>
        public static PyList AsList(PyObject value)
        {
            IntPtr op = Runtime.PySequence_List(value.obj);

            if (op == IntPtr.Zero)
            {
                throw PythonException.ThrowLastAsClrException();
            }
            return(new PyList(op));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Contains Method
        /// </summary>
        /// <remarks>
        /// Return true if the sequence contains the given item. This method
        /// throws a PythonException if an error occurs during the check.
        /// </remarks>
        public bool Contains(PyObject item)
        {
            int r = Runtime.PySequence_Contains(obj, item.obj);

            if (r < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
            return(r != 0);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Values Method
        /// </summary>
        /// <remarks>
        /// Returns a sequence containing the values of the dictionary.
        /// </remarks>
        public PyObject Values()
        {
            IntPtr items = Runtime.PyDict_Values(obj);

            if (items == IntPtr.Zero)
            {
                throw PythonException.ThrowLastAsClrException();
            }
            return(new PyObject(items));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Repeat Method
        /// </summary>
        /// <remarks>
        /// Return the sequence object repeated N times. This is equivalent
        /// to the Python expression "object * count".
        /// </remarks>
        public PyObject Repeat(int count)
        {
            IntPtr op = Runtime.PySequence_Repeat(obj, count);

            if (op == IntPtr.Zero)
            {
                throw PythonException.ThrowLastAsClrException();
            }
            return(new PyObject(op));
        }
Ejemplo n.º 28
0
        /// <summary>
        /// GetSlice Method
        /// </summary>
        /// <remarks>
        /// Return the slice of the sequence with the given indices.
        /// </remarks>
        public PyObject GetSlice(int i1, int i2)
        {
            IntPtr op = Runtime.PySequence_GetSlice(obj, i1, i2);

            if (op == IntPtr.Zero)
            {
                throw PythonException.ThrowLastAsClrException();
            }
            return(new PyObject(op));
        }
Ejemplo n.º 29
0
 /// <summary>
 /// FillInfo Method
 /// </summary>
 /// <remarks>
 /// Handle buffer requests for an exporter that wants to expose buf of size len with writability set according to readonly. buf is interpreted as a sequence of unsigned bytes.
 /// The flags argument indicates the request type. This function always fills in view as specified by flags, unless buf has been designated as read-only and PyBUF_WRITABLE is set in flags.
 /// On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise PyExc_BufferError, set view->obj to NULL and return -1;
 /// If this function is used as part of a getbufferproc, exporter MUST be set to the exporting object and flags must be passed unmodified.Otherwise, exporter MUST be NULL.
 /// </remarks>
 /// <returns>On success, set view->obj to a new reference to exporter and return 0. Otherwise, raise PyExc_BufferError, set view->obj to NULL and return -1;</returns>
 public void FillInfo(IntPtr exporter, IntPtr buf, long len, bool _readonly, int flags)
 {
     if (disposedValue)
     {
         throw new ObjectDisposedException(nameof(PyBuffer));
     }
     if (Runtime.PyBuffer_FillInfo(ref _view, exporter, buf, (IntPtr)len, Convert.ToInt32(_readonly), flags) < 0)
     {
         throw PythonException.ThrowLastAsClrException();
     }
 }
Ejemplo n.º 30
0
        /// <summary>
        /// Copy len bytes from view to its contiguous representation in buf. order can be 'C' or 'F' or 'A' (for C-style or Fortran-style ordering or either one). 0 is returned on success, -1 on error.
        /// </summary>
        /// <param name="order">order can be 'C' or 'F' or 'A' (for C-style or Fortran-style ordering or either one).</param>
        /// <param name="buf">Buffer to copy to</param>
        public void ToContiguous(IntPtr buf, BufferOrderStyle order)
        {
            if (disposedValue)
            {
                throw new ObjectDisposedException(nameof(PyBuffer));
            }

            if (Runtime.PyBuffer_ToContiguous(buf, ref _view, _view.len, OrderStyleToChar(order, true)) < 0)
            {
                throw PythonException.ThrowLastAsClrException();
            }
        }