PyTuple_SetItem() private method

private PyTuple_SetItem ( IntPtr pointer, int index, IntPtr value ) : int
pointer IntPtr
index int
value IntPtr
return int
Esempio n. 1
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()));
        }
Esempio n. 2
0
        /// <summary>
        /// This will return default arguments a new instance of a tuple. The size
        /// of the tuple will indicate the number of default arguments.
        /// </summary>
        /// <param name="args">This is pointing to the tuple args passed in</param>
        /// <returns>a new instance of the tuple containing the default args</returns>
        internal IntPtr GetDefaultArgs(IntPtr args)
        {
            // if we don't need default args return empty tuple
            if (!NeedsDefaultArgs(args))
            {
                return(Runtime.PyTuple_New(0));
            }
            var pynargs = Runtime.PyTuple_Size(args);

            // Get the default arg tuple
            MethodBase[] methods = SetterBinder.GetMethods();
            MethodBase   mi      = methods[0];

            ParameterInfo[] pi          = mi.GetParameters();
            int             clrnargs    = pi.Length - 1;
            IntPtr          defaultArgs = Runtime.PyTuple_New(clrnargs - pynargs);

            for (var i = 0; i < clrnargs - pynargs; i++)
            {
                if (pi[i + pynargs].DefaultValue == DBNull.Value)
                {
                    continue;
                }
                IntPtr arg = Converter.ToPython(pi[i + pynargs].DefaultValue, pi[i + pynargs].ParameterType);
                Runtime.PyTuple_SetItem(defaultArgs, i, arg);
            }
            return(defaultArgs);
        }
Esempio n. 3
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());
            }
        }
Esempio n. 4
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 bool SetArgsAndCause(BorrowedReference ob, Exception e)
        {
            NewReference args;

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

            using (args)
            {
                if (Runtime.PyObject_SetAttrString(ob, "args", args.Borrow()) != 0)
                {
                    return(false);
                }
            }

            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());
            }

            return(true);
        }
Esempio 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>
        /// <param name="ob">The python object wrapping </param>
        internal static void SetArgsAndCause(Exception e, IntPtr ob)
        {
            IntPtr args;

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

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

            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.DangerousMoveToPointer());
            }
        }
Esempio n. 6
0
        //====================================================================
        // Exceptions __getattribute__ implementation.
        // handles Python's args and message attributes
        //====================================================================

        public static IntPtr tp_getattro(IntPtr ob, IntPtr key)
        {
            if (!Runtime.PyString_Check(key))
            {
                Exceptions.SetError(Exceptions.TypeError, "string expected");
                return(IntPtr.Zero);
            }

            string name = Runtime.GetManagedString(key);

            if (name == "args")
            {
                Exception e = ToException(ob);
                IntPtr    args;
                if (e.Message != String.Empty)
                {
                    args = Runtime.PyTuple_New(1);
                    IntPtr msg = Runtime.PyUnicode_FromString(e.Message);
                    Runtime.PyTuple_SetItem(args, 0, msg);
                }
                else
                {
                    args = Runtime.PyTuple_New(0);
                }
                return(args);
            }

            if (name == "message")
            {
                return(ExceptionClassObject.tp_str(ob));
            }

            return(Runtime.PyObject_GenericGetAttr(ob, key));
        }
Esempio n. 7
0
        //====================================================================
        // helper methods for raising warnings
        //====================================================================

        /// <summary>
        /// Alias for Python's warnings.warn() function.
        /// </summary>
        public static void warn(string message, IntPtr exception, int stacklevel)
        {
            if (exception == IntPtr.Zero ||
                (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1))
            {
                Exceptions.RaiseTypeError("Invalid exception");
            }

            Runtime.XIncref(warnings_module);
            IntPtr warn = Runtime.PyObject_GetAttrString(warnings_module, "warn");

            Runtime.XDecref(warnings_module);
            Exceptions.ErrorCheck(warn);

            IntPtr args = Runtime.PyTuple_New(3);
            IntPtr msg  = Runtime.PyString_FromString(message);

            Runtime.XIncref(exception); // PyTuple_SetItem steals a reference
            IntPtr level = Runtime.PyInt_FromInt32(stacklevel);

            Runtime.PyTuple_SetItem(args, 0, msg);
            Runtime.PyTuple_SetItem(args, 1, exception);
            Runtime.PyTuple_SetItem(args, 2, level);

            IntPtr result = Runtime.PyObject_CallObject(warn, args);

            Exceptions.ErrorCheck(result);

            Runtime.XDecref(warn);
            Runtime.XDecref(result);
            Runtime.XDecref(args);
        }
Esempio n. 8
0
        /// <summary>
        /// This will return default arguments a new instance of a tuple. The size
        /// of the tuple will indicate the number of default arguments.
        /// </summary>
        /// <param name="args">This is pointing to the tuple args passed in</param>
        /// <returns>a new instance of the tuple containing the default args</returns>
        internal NewReference GetDefaultArgs(BorrowedReference args)
        {
            // if we don't need default args return empty tuple
            if (!NeedsDefaultArgs(args))
            {
                return(Runtime.PyTuple_New(0));
            }
            var pynargs = Runtime.PyTuple_Size(args);

            // Get the default arg tuple
            var        methods = SetterBinder.GetMethods();
            MethodBase mi      = methods[0].MethodBase;

            ParameterInfo[] pi          = mi.GetParameters();
            int             clrnargs    = pi.Length - 1;
            var             defaultArgs = Runtime.PyTuple_New(clrnargs - pynargs);

            for (var i = 0; i < clrnargs - pynargs; i++)
            {
                if (pi[i + pynargs].DefaultValue == DBNull.Value)
                {
                    continue;
                }
                using var arg = Converter.ToPython(pi[i + pynargs].DefaultValue, pi[i + pynargs].ParameterType);
                Runtime.PyTuple_SetItem(defaultArgs.Borrow(), i, arg.Steal());
            }
            return(defaultArgs);
        }
Esempio n. 9
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>
        /// <param name="ob">The python object wrapping </param>
        internal static void SetArgsAndCause(IntPtr ob)
        {
            // e: A CLR Exception
            Exception e = ExceptionClassObject.ToException(ob);

            if (e == null)
            {
                return;
            }

            IntPtr args;

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

            Marshal.WriteIntPtr(ob, ExceptionOffset.args, args);

#if PYTHON3
            if (e.InnerException != null)
            {
                IntPtr cause = CLRObject.GetInstHandle(e.InnerException);
                Marshal.WriteIntPtr(ob, ExceptionOffset.cause, cause);
            }
#endif
        }
Esempio n. 10
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);
        }
Esempio n. 11
0
        //====================================================================
        // Implements __setitem__ for reflected classes and value types.
        //====================================================================

        public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v)
        {
            //ManagedType self = GetManagedObject(ob);
            IntPtr    tp  = Runtime.PyObject_TYPE(ob);
            ClassBase cls = (ClassBase)GetManagedObject(tp);

            if (cls.indexer == null || !cls.indexer.CanSet)
            {
                Exceptions.SetError(Exceptions.TypeError,
                                    "object doesn't support item assignment"
                                    );
                return(-1);
            }

            // Arg may be a tuple in the case of an indexer with multiple
            // parameters. If so, use it directly, else make a new tuple
            // with the index arg (method binders expect arg tuples).

            IntPtr args = idx;
            bool   free = false;

            if (!Runtime.PyTuple_Check(idx))
            {
                args = Runtime.PyTuple_New(1);
                Runtime.Incref(idx);
                Runtime.PyTuple_SetItem(args, 0, idx);
                free = true;
            }

            int    i    = Runtime.PyTuple_Size(args);
            IntPtr real = Runtime.PyTuple_New(i + 1);

            for (int n = 0; n < i; n++)
            {
                IntPtr item = Runtime.PyTuple_GetItem(args, n);
                Runtime.Incref(item);
                Runtime.PyTuple_SetItem(real, n, item);
            }
            Runtime.Incref(v);
            Runtime.PyTuple_SetItem(real, i, v);

            try {
                cls.indexer.SetItem(ob, real);
            }
            finally {
                Runtime.Decref(real);

                if (free)
                {
                    Runtime.Decref(args);
                }
            }

            if (Exceptions.ErrorOccurred())
            {
                return(-1);
            }

            return(0);
        }
Esempio n. 12
0
        private static void AddArgument(IntPtr argtuple, int i, object target)
        {
            IntPtr ptr = GetPythonObject(target);

            if (Runtime.PyTuple_SetItem(argtuple, i, ptr) < 0)
            {
                throw new PythonException();
            }
        }
Esempio n. 13
0
        /// <summary>
        /// PyTuple Constructor
        /// </summary>
        /// <remarks>
        /// Creates a new PyTuple from an array of PyObject instances.
        /// <para />
        /// See caveats about PyTuple_SetItem:
        /// https://www.coursehero.com/file/p4j2ogg/important-exceptions-to-this-rule-PyTupleSetItem-and-PyListSetItem-These/
        /// </remarks>
        public PyTuple(PyObject[] items)
        {
            int count = items.Length;

            obj = Runtime.PyTuple_New(count);
            for (var i = 0; i < count; i++)
            {
                IntPtr ptr = items[i].obj;
                Runtime.XIncref(ptr);
                int res = Runtime.PyTuple_SetItem(obj, i, ptr);
                PythonException.ThrowIfIsNotZero(res);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// PyTuple Constructor
        /// </summary>
        /// <remarks>
        /// Creates a new PyTuple from an array of PyObject instances.
        /// <para />
        /// See caveats about PyTuple_SetItem:
        /// https://www.coursehero.com/file/p4j2ogg/important-exceptions-to-this-rule-PyTupleSetItem-and-PyListSetItem-These/
        /// </remarks>
        public PyTuple(PyObject[] items)
        {
            int count = items.Length;

            obj = Runtime.PyTuple_New(count);
            for (var i = 0; i < count; i++)
            {
                IntPtr ptr = items[i].obj;
                Runtime.XIncref(ptr);
                Runtime.PyTuple_SetItem(obj, i, ptr);
                Runtime.CheckExceptionOccurred();
            }
        }
Esempio n. 15
0
        private static IntPtr TzInfo(DateTimeKind kind)
        {
            if (kind == DateTimeKind.Unspecified)
            {
                return(Runtime.PyNone);
            }
            var    offset     = kind == DateTimeKind.Local ? DateTimeOffset.Now.Offset : TimeSpan.Zero;
            IntPtr tzInfoArgs = Runtime.PyTuple_New(2);

            Runtime.PyTuple_SetItem(tzInfoArgs, 0, Runtime.PyFloat_FromDouble(offset.Hours));
            Runtime.PyTuple_SetItem(tzInfoArgs, 1, Runtime.PyFloat_FromDouble(offset.Minutes));
            return(Runtime.PyObject_CallObject(tzInfoCtor, tzInfoArgs));
        }
Esempio n. 16
0
        /// <summary>
        /// PyTuple Constructor
        /// </summary>
        ///
        /// <remarks>
        /// Creates a new PyTuple from an array of PyObject instances.
        /// </remarks>
        public PyTuple(PyObject[] items) : base()
        {
            int count = items.Length;

            obj = Runtime.PyTuple_New(count);
            for (int i = 0; i < count; i++)
            {
                IntPtr ptr = items[i].obj;
                Runtime.XIncref(ptr);
                int r = Runtime.PyTuple_SetItem(obj, i, ptr);
                if (r < 0)
                {
                    throw new PythonException();
                }
            }
        }
Esempio n. 17
0
        private void GetArgs(object[] inargs, out PyTuple args, out PyDict kwargs)
        {
            int arg_count;

            for (arg_count = 0; arg_count < inargs.Length && !(inargs[arg_count] is Py.KeywordArguments); ++arg_count)
            {
                ;
            }
            IntPtr argtuple = Runtime.PyTuple_New(arg_count);

            for (int i = 0; i < arg_count; i++)
            {
                IntPtr ptr;
                if (inargs[i] is PyObject)
                {
                    ptr = ((PyObject)inargs[i]).Handle;
                    Runtime.Incref(ptr);
                }
                else
                {
                    ptr = Converter.ToPython(inargs[i], inargs[i].GetType());
                }
                if (Runtime.PyTuple_SetItem(argtuple, i, ptr) < 0)
                {
                    throw new PythonException();
                }
            }
            args   = new PyTuple(argtuple);
            kwargs = null;
            for (int i = arg_count; i < inargs.Length; i++)
            {
                if (!(inargs[i] is Py.KeywordArguments))
                {
                    throw new ArgumentException("Keyword arguments must come after normal arguments.");
                }
                if (kwargs == null)
                {
                    kwargs = (Py.KeywordArguments)inargs[i];
                }
                else
                {
                    kwargs.Update((Py.KeywordArguments)inargs[i]);
                }
            }
        }
Esempio n. 18
0
        private static IntPtr FromArray(PyObject[] items)
        {
            int    count = items.Length;
            IntPtr val   = Runtime.PyTuple_New(count);

            for (var i = 0; i < count; i++)
            {
                IntPtr ptr = items[i].obj;
                Runtime.XIncref(ptr);
                int res = Runtime.PyTuple_SetItem(val, i, ptr);
                if (res != 0)
                {
                    Runtime.Py_DecRef(val);
                    throw PythonException.ThrowLastAsClrException();
                }
            }
            return(val);
        }
Esempio n. 19
0
        //====================================================================
        // Implements __getitem__ for reflected classes and value types.
        //====================================================================

        public static IntPtr mp_subscript(IntPtr ob, IntPtr idx)
        {
            //ManagedType self = GetManagedObject(ob);
            IntPtr    tp  = Runtime.PyObject_TYPE(ob);
            ClassBase cls = (ClassBase)GetManagedObject(tp);

            if (cls.indexer == null || !cls.indexer.CanGet)
            {
                Exceptions.SetError(Exceptions.TypeError,
                                    "unindexable object"
                                    );
                return(IntPtr.Zero);
            }

            // Arg may be a tuple in the case of an indexer with multiple
            // parameters. If so, use it directly, else make a new tuple
            // with the index arg (method binders expect arg tuples).

            IntPtr args = idx;
            bool   free = false;

            if (!Runtime.PyTuple_Check(idx))
            {
                args = Runtime.PyTuple_New(1);
                Runtime.XIncref(idx);
                Runtime.PyTuple_SetItem(args, 0, idx);
                free = true;
            }

            IntPtr value = IntPtr.Zero;

            try
            {
                value = cls.indexer.GetItem(ob, args);
            }
            finally
            {
                if (free)
                {
                    Runtime.XDecref(args);
                }
            }
            return(value);
        }
Esempio n. 20
0
        public object TrueDispatch(ArrayList args)
        {
            MethodInfo method = dtype.GetMethod("Invoke");

            ParameterInfo[] pi     = method.GetParameters();
            IntPtr          pyargs = Runtime.PyTuple_New(pi.Length);
            Type            rtype  = method.ReturnType;

            for (int i = 0; i < pi.Length; i++)
            {
                // Here we own the reference to the Python value, and we
                // give the ownership to the arg tuple.
                IntPtr arg = Converter.ToPython(args[i], pi[i].ParameterType);
                Runtime.PyTuple_SetItem(pyargs, i, arg);
            }

            IntPtr op = Runtime.PyObject_Call(target, pyargs, IntPtr.Zero);

            Runtime.Decref(pyargs);

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

            if (rtype == typeof(void))
            {
                return(null);
            }

            Object result = null;

            if (!Converter.ToManaged(op, rtype, out result, false))
            {
                string s = "could not convert Python result to " +
                           rtype.ToString();
                Runtime.Decref(op);
                throw new ConversionException(s);
            }

            Runtime.Decref(op);
            return(result);
        }
Esempio n. 21
0
        public static IntPtr tp_repr(IntPtr ob)
        {
            var co = GetManagedObject(ob) as CLRObject;

            if (co == null)
            {
                return(Exceptions.RaiseTypeError("invalid object"));
            }
            try
            {
                //if __repr__ is defined, use it
                var instType = co.inst.GetType();
                System.Reflection.MethodInfo methodInfo = instType.GetMethod("__repr__");
                if (methodInfo != null && methodInfo.IsPublic)
                {
                    var reprString = methodInfo.Invoke(co.inst, null) as string;
                    return(Runtime.PyString_FromString(reprString));
                }

                //otherwise use the standard object.__repr__(inst)
                IntPtr args = Runtime.PyTuple_New(1);
                Runtime.XIncref(ob);
                Runtime.PyTuple_SetItem(args, 0, ob);
                IntPtr reprFunc = Runtime.PyObject_GetAttr(Runtime.PyBaseObjectType, PyIdentifier.__repr__);
                var    output   = Runtime.PyObject_Call(reprFunc, args, IntPtr.Zero);
                Runtime.XDecref(args);
                Runtime.XDecref(reprFunc);
                return(output);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                Exceptions.SetError(e);
                return(IntPtr.Zero);
            }
        }
Esempio n. 22
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);
        }
Esempio n. 23
0
        /// <summary>
        /// PyTuple Constructor
        /// </summary>
        /// <remarks>
        /// Creates a new PyTuple from an array of PyObject instances.
        /// <para />
        /// See caveats about PyTuple_SetItem:
        /// https://www.coursehero.com/file/p4j2ogg/important-exceptions-to-this-rule-PyTupleSetItem-and-PyListSetItem-These/
        /// </remarks>
        public PyTuple(PyObject[] items)
        {
            int count = items.Length;

            obj = Runtime.PyTuple_New(count);
            if (obj == IntPtr.Zero)
            {
                throw new PythonException();
            }
            for (int i = 0; i < count; i++)
            {
                IntPtr ptr = items[i].obj;
                Runtime.XIncref(ptr);
                if (Runtime.PyTuple_SetItem(obj, i, ptr) != 0)
                {
                    for (int j = i; j >= 0; j--)
                    {
                        Runtime.XDecref(items[j].obj);
                    }
                    throw new PythonException();
                }
            }
        }
Esempio n. 24
0
        //====================================================================
        // helper methods for raising warnings
        //====================================================================

        /// <summary>
        /// Alias for Python's warnings.warn() function.
        /// </summary>
        public static void warn(string message, BorrowedReference exception, int stacklevel)
        {
            if (exception == null ||
                (Runtime.PyObject_IsSubclass(exception, Exceptions.Warning) != 1))
            {
                Exceptions.RaiseTypeError("Invalid exception");
            }

            using var warn = Runtime.PyObject_GetAttrString(warnings_module.obj, "warn");
            Exceptions.ErrorCheck(warn.Borrow());

            using var argsTemp = Runtime.PyTuple_New(3);
            BorrowedReference args = argsTemp.BorrowOrThrow();

            using var msg = Runtime.PyString_FromString(message);
            Runtime.PyTuple_SetItem(args, 0, msg.StealOrThrow());
            Runtime.PyTuple_SetItem(args, 1, exception);

            using var level = Runtime.PyInt_FromInt32(stacklevel);
            Runtime.PyTuple_SetItem(args, 2, level.StealOrThrow());

            using var result = Runtime.PyObject_CallObject(warn.Borrow(), args);
            Exceptions.ErrorCheck(result.Borrow());
        }
Esempio n. 25
0
        internal static IntPtr ToPython(object value, Type type)
        {
            if (value is PyObject)
            {
                IntPtr handle = ((PyObject)value).Handle;
                Runtime.XIncref(handle);
                return(handle);
            }
            IntPtr result = IntPtr.Zero;

            // Null always converts to None in Python.

            if (value == null)
            {
                result = Runtime.PyNone;
                Runtime.XIncref(result);
                return(result);
            }

            if (value is IList && value.GetType().IsGenericType)
            {
                using (var resultlist = new PyList())
                {
                    foreach (object o in (IEnumerable)value)
                    {
                        using (var p = new PyObject(ToPython(o, o?.GetType())))
                        {
                            resultlist.Append(p);
                        }
                    }
                    Runtime.XIncref(resultlist.Handle);
                    return(resultlist.Handle);
                }
            }

            // it the type is a python subclass of a managed type then return the
            // underlying python object rather than construct a new wrapper object.
            var pyderived = value as IPythonDerivedType;

            if (null != pyderived)
            {
                return(ClassDerivedObject.ToPython(pyderived));
            }

            // hmm - from Python, we almost never care what the declared
            // type is. we'd rather have the object bound to the actual
            // implementing class.

            type = value.GetType();

            TypeCode tc = Type.GetTypeCode(type);

            switch (tc)
            {
            case TypeCode.Object:
                if (value is TimeSpan)
                {
                    var timespan = (TimeSpan)value;

                    IntPtr timeSpanArgs = Runtime.PyTuple_New(1);
                    Runtime.PyTuple_SetItem(timeSpanArgs, 0, Runtime.PyFloat_FromDouble(timespan.TotalDays));
                    return(Runtime.PyObject_CallObject(timeSpanCtor, timeSpanArgs));
                }
                return(CLRObject.GetInstHandle(value, type));

            case TypeCode.String:
                return(Runtime.PyUnicode_FromString((string)value));

            case TypeCode.Int32:
                return(Runtime.PyInt_FromInt32((int)value));

            case TypeCode.Boolean:
                if ((bool)value)
                {
                    Runtime.XIncref(Runtime.PyTrue);
                    return(Runtime.PyTrue);
                }
                Runtime.XIncref(Runtime.PyFalse);
                return(Runtime.PyFalse);

            case TypeCode.Byte:
                return(Runtime.PyInt_FromInt32((int)((byte)value)));

            case TypeCode.Char:
                return(Runtime.PyUnicode_FromOrdinal((int)((char)value)));

            case TypeCode.Int16:
                return(Runtime.PyInt_FromInt32((int)((short)value)));

            case TypeCode.Int64:
                return(Runtime.PyLong_FromLongLong((long)value));

            case TypeCode.Single:
                // return Runtime.PyFloat_FromDouble((double)((float)value));
                string ss = ((float)value).ToString(nfi);
                IntPtr ps = Runtime.PyString_FromString(ss);
                IntPtr op = Runtime.PyFloat_FromString(ps, IntPtr.Zero);
                Runtime.XDecref(ps);
                return(op);

            case TypeCode.Double:
                return(Runtime.PyFloat_FromDouble((double)value));

            case TypeCode.SByte:
                return(Runtime.PyInt_FromInt32((int)((sbyte)value)));

            case TypeCode.UInt16:
                return(Runtime.PyInt_FromInt32((int)((ushort)value)));

            case TypeCode.UInt32:
                return(Runtime.PyLong_FromUnsignedLong((uint)value));

            case TypeCode.UInt64:
                return(Runtime.PyLong_FromUnsignedLongLong((ulong)value));

            case TypeCode.Decimal:
                string d2s         = ((decimal)value).ToString(nfi);
                IntPtr d2p         = Runtime.PyString_FromString(d2s);
                IntPtr decimalArgs = Runtime.PyTuple_New(1);
                Runtime.PyTuple_SetItem(decimalArgs, 0, d2p);

                return(Runtime.PyObject_CallObject(decimalCtor, decimalArgs));

            case TypeCode.DateTime:
                var datetime = (DateTime)value;

                IntPtr dateTimeArgs = Runtime.PyTuple_New(8);
                Runtime.PyTuple_SetItem(dateTimeArgs, 0, Runtime.PyInt_FromInt32(datetime.Year));
                Runtime.PyTuple_SetItem(dateTimeArgs, 1, Runtime.PyInt_FromInt32(datetime.Month));
                Runtime.PyTuple_SetItem(dateTimeArgs, 2, Runtime.PyInt_FromInt32(datetime.Day));
                Runtime.PyTuple_SetItem(dateTimeArgs, 3, Runtime.PyInt_FromInt32(datetime.Hour));
                Runtime.PyTuple_SetItem(dateTimeArgs, 4, Runtime.PyInt_FromInt32(datetime.Minute));
                Runtime.PyTuple_SetItem(dateTimeArgs, 5, Runtime.PyInt_FromInt32(datetime.Second));
                Runtime.PyTuple_SetItem(dateTimeArgs, 6, Runtime.PyInt_FromInt32(1000 * datetime.Millisecond));
                Runtime.PyTuple_SetItem(dateTimeArgs, 7, TzInfo(datetime.Kind));

                return(Runtime.PyObject_CallObject(dateTimeCtor, dateTimeArgs));

            default:
                if (value is IEnumerable)
                {
                    using (var resultlist = new PyList())
                    {
                        foreach (object o in (IEnumerable)value)
                        {
                            using (var p = new PyObject(ToPython(o, o?.GetType())))
                            {
                                resultlist.Append(p);
                            }
                        }
                        Runtime.XIncref(resultlist.Handle);
                        return(resultlist.Handle);
                    }
                }
                result = CLRObject.GetInstHandle(value, type);
                return(result);
            }
        }
Esempio n. 26
0
        internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo)
        {
            Binding binding = Bind(inst, args, kw, info, methodinfo);
            object  result;
            IntPtr  ts = IntPtr.Zero;

            if (binding == null)
            {
                var value = new StringBuilder("No method matches given arguments");
                if (methodinfo != null && methodinfo.Length > 0)
                {
                    value.Append($" for {methodinfo[0].Name}");
                }

                value.Append(": ");
                AppendArgumentTypes(to: value, args);
                Exceptions.SetError(Exceptions.TypeError, value.ToString());
                return(IntPtr.Zero);
            }

            if (allow_threads)
            {
                ts = PythonEngine.BeginAllowThreads();
            }

            try
            {
                result = binding.info.Invoke(binding.inst, BindingFlags.Default, null, binding.args, null);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                if (allow_threads)
                {
                    PythonEngine.EndAllowThreads(ts);
                }
                Exceptions.SetError(e);
                return(IntPtr.Zero);
            }

            if (allow_threads)
            {
                PythonEngine.EndAllowThreads(ts);
            }

            // If there are out parameters, we return a tuple containing
            // the result followed by the out parameters. If there is only
            // one out parameter and the return type of the method is void,
            // we return the out parameter as the result to Python (for
            // code compatibility with ironpython).

            var mi = (MethodInfo)binding.info;

            if (binding.outs == 1 && mi.ReturnType == typeof(void))
            {
            }

            if (binding.outs > 0)
            {
                ParameterInfo[] pi = mi.GetParameters();
                int             c  = pi.Length;
                var             n  = 0;

                IntPtr t = Runtime.PyTuple_New(binding.outs + 1);
                IntPtr v = Converter.ToPython(result, mi.ReturnType);
                Runtime.PyTuple_SetItem(t, n, v);
                n++;

                for (var i = 0; i < c; i++)
                {
                    Type pt = pi[i].ParameterType;
                    if (pi[i].IsOut || pt.IsByRef)
                    {
                        v = Converter.ToPython(binding.args[i], pt);
                        Runtime.PyTuple_SetItem(t, n, v);
                        n++;
                    }
                }

                if (binding.outs == 1 && mi.ReturnType == typeof(void))
                {
                    v = Runtime.PyTuple_GetItem(t, 1);
                    Runtime.XIncref(v);
                    Runtime.XDecref(t);
                    return(v);
                }

                return(t);
            }

            return(Converter.ToPython(result, mi.ReturnType));
        }
Esempio n. 27
0
        /// <summary>
        /// Standard comparison implementation for instances of reflected types.
        /// </summary>
        public static IntPtr tp_richcompare(IntPtr ob, IntPtr other, int op)
        {
            CLRObject co1;
            CLRObject co2;
            IntPtr    tp  = Runtime.PyObject_TYPE(ob);
            var       cls = (ClassBase)GetManagedObject(tp);

            // C# operator methods take precedence over IComparable.
            // We first check if there's a comparison operator by looking up the richcompare table,
            // otherwise fallback to checking if an IComparable interface is handled.
            if (cls.richcompare.TryGetValue(op, out var methodObject))
            {
                // Wrap the `other` argument of a binary comparison operator in a PyTuple.
                IntPtr args = Runtime.PyTuple_New(1);
                Runtime.XIncref(other);
                Runtime.PyTuple_SetItem(args, 0, other);

                IntPtr value;
                try
                {
                    value = methodObject.Invoke(ob, args, IntPtr.Zero);
                }
                finally
                {
                    Runtime.XDecref(args);  // Free args pytuple
                }
                return(value);
            }

            switch (op)
            {
            case Runtime.Py_EQ:
            case Runtime.Py_NE:
                IntPtr pytrue  = Runtime.PyTrue;
                IntPtr pyfalse = Runtime.PyFalse;

                // swap true and false for NE
                if (op != Runtime.Py_EQ)
                {
                    pytrue  = Runtime.PyFalse;
                    pyfalse = Runtime.PyTrue;
                }

                if (ob == other)
                {
                    Runtime.XIncref(pytrue);
                    return(pytrue);
                }

                co1 = GetManagedObject(ob) as CLRObject;
                co2 = GetManagedObject(other) as CLRObject;
                if (null == co2)
                {
                    Runtime.XIncref(pyfalse);
                    return(pyfalse);
                }

                object o1 = co1.inst;
                object o2 = co2.inst;

                if (Equals(o1, o2))
                {
                    Runtime.XIncref(pytrue);
                    return(pytrue);
                }

                Runtime.XIncref(pyfalse);
                return(pyfalse);

            case Runtime.Py_LT:
            case Runtime.Py_LE:
            case Runtime.Py_GT:
            case Runtime.Py_GE:
                co1 = GetManagedObject(ob) as CLRObject;
                co2 = GetManagedObject(other) as CLRObject;
                if (co1 == null || co2 == null)
                {
                    return(Exceptions.RaiseTypeError("Cannot get managed object"));
                }
                var co1Comp = co1.inst as IComparable;
                if (co1Comp == null)
                {
                    Type co1Type = co1.GetType();
                    return(Exceptions.RaiseTypeError($"Cannot convert object of type {co1Type} to IComparable"));
                }
                try
                {
                    int cmp = co1Comp.CompareTo(co2.inst);

                    IntPtr pyCmp;
                    if (cmp < 0)
                    {
                        if (op == Runtime.Py_LT || op == Runtime.Py_LE)
                        {
                            pyCmp = Runtime.PyTrue;
                        }
                        else
                        {
                            pyCmp = Runtime.PyFalse;
                        }
                    }
                    else if (cmp == 0)
                    {
                        if (op == Runtime.Py_LE || op == Runtime.Py_GE)
                        {
                            pyCmp = Runtime.PyTrue;
                        }
                        else
                        {
                            pyCmp = Runtime.PyFalse;
                        }
                    }
                    else
                    {
                        if (op == Runtime.Py_GE || op == Runtime.Py_GT)
                        {
                            pyCmp = Runtime.PyTrue;
                        }
                        else
                        {
                            pyCmp = Runtime.PyFalse;
                        }
                    }
                    Runtime.XIncref(pyCmp);
                    return(pyCmp);
                }
                catch (ArgumentException e)
                {
                    return(Exceptions.RaiseTypeError(e.Message));
                }

            default:
                Runtime.XIncref(Runtime.PyNotImplemented);
                return(Runtime.PyNotImplemented);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// Implements __setitem__ for reflected classes and value types.
        /// </summary>
        public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v)
        {
            IntPtr tp  = Runtime.PyObject_TYPE(ob);
            var    cls = (ClassBase)GetManagedObject(tp);

            if (cls.indexer == null || !cls.indexer.CanSet)
            {
                Exceptions.SetError(Exceptions.TypeError, "object doesn't support item assignment");
                return(-1);
            }

            // Arg may be a tuple in the case of an indexer with multiple
            // parameters. If so, use it directly, else make a new tuple
            // with the index arg (method binders expect arg tuples).
            IntPtr args = idx;
            var    free = false;

            if (!Runtime.PyTuple_Check(idx))
            {
                args = Runtime.PyTuple_New(1);
                Runtime.XIncref(idx);
                Runtime.PyTuple_SetItem(args, 0, idx);
                free = true;
            }

            // Get the args passed in.
            var    i                = Runtime.PyTuple_Size(args);
            IntPtr defaultArgs      = cls.indexer.GetDefaultArgs(args);
            var    numOfDefaultArgs = Runtime.PyTuple_Size(defaultArgs);
            var    temp             = i + numOfDefaultArgs;
            IntPtr real             = Runtime.PyTuple_New(temp + 1);

            for (var n = 0; n < i; n++)
            {
                IntPtr item = Runtime.PyTuple_GetItem(args, n);
                Runtime.XIncref(item);
                Runtime.PyTuple_SetItem(real, n, item);
            }

            // Add Default Args if needed
            for (var n = 0; n < numOfDefaultArgs; n++)
            {
                IntPtr item = Runtime.PyTuple_GetItem(defaultArgs, n);
                Runtime.XIncref(item);
                Runtime.PyTuple_SetItem(real, n + i, item);
            }
            // no longer need defaultArgs
            Runtime.XDecref(defaultArgs);
            i = temp;

            // Add value to argument list
            Runtime.XIncref(v);
            Runtime.PyTuple_SetItem(real, i, v);

            try
            {
                cls.indexer.SetItem(ob, real);
            }
            finally
            {
                Runtime.XDecref(real);

                if (free)
                {
                    Runtime.XDecref(args);
                }
            }

            if (Exceptions.ErrorOccurred())
            {
                return(-1);
            }

            return(0);
        }
Esempio n. 29
0
        internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, MethodBase info, MethodInfo[] methodinfo)
        {
            // No valid methods, nothing to bind.
            if (GetMethods().Length == 0)
            {
                var msg = new StringBuilder("The underlying C# method(s) have been deleted");
                if (list.Count > 0 && list[0].Name != null)
                {
                    msg.Append($": {list[0]}");
                }
                return(Exceptions.RaiseTypeError(msg.ToString()));
            }

            Binding binding = Bind(inst, args, kw, info, methodinfo);
            object  result;
            IntPtr  ts = IntPtr.Zero;

            if (binding == null)
            {
                var value = new StringBuilder("No method matches given arguments");
                if (methodinfo != null && methodinfo.Length > 0)
                {
                    value.Append($" for {methodinfo[0].Name}");
                }
                else if (list.Count > 0 && list[0].Valid)
                {
                    value.Append($" for {list[0].Value.Name}");
                }

                value.Append(": ");
                Runtime.PyErr_Fetch(out var errType, out var errVal, out var errTrace);
                AppendArgumentTypes(to: value, args);
                Runtime.PyErr_Restore(errType.StealNullable(), errVal.StealNullable(), errTrace.StealNullable());
                Exceptions.RaiseTypeError(value.ToString());
                return(IntPtr.Zero);
            }

            if (allow_threads)
            {
                ts = PythonEngine.BeginAllowThreads();
            }

            try
            {
                result = binding.info.Invoke(binding.inst, BindingFlags.Default, null, binding.args, null);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                if (allow_threads)
                {
                    PythonEngine.EndAllowThreads(ts);
                }
                Exceptions.SetError(e);
                return(IntPtr.Zero);
            }

            if (allow_threads)
            {
                PythonEngine.EndAllowThreads(ts);
            }

            // If there are out parameters, we return a tuple containing
            // the result, if any, followed by the out parameters. If there is only
            // one out parameter and the return type of the method is void,
            // we return the out parameter as the result to Python (for
            // code compatibility with ironpython).

            var mi = (MethodInfo)binding.info;

            if (binding.outs > 0)
            {
                ParameterInfo[] pi = mi.GetParameters();
                int             c  = pi.Length;
                var             n  = 0;

                bool   isVoid    = mi.ReturnType == typeof(void);
                int    tupleSize = binding.outs + (isVoid ? 0 : 1);
                IntPtr t         = Runtime.PyTuple_New(tupleSize);
                if (!isVoid)
                {
                    IntPtr v = Converter.ToPython(result, mi.ReturnType);
                    Runtime.PyTuple_SetItem(t, n, v);
                    n++;
                }

                for (var i = 0; i < c; i++)
                {
                    Type pt = pi[i].ParameterType;
                    if (pt.IsByRef)
                    {
                        IntPtr v = Converter.ToPython(binding.args[i], pt.GetElementType());
                        Runtime.PyTuple_SetItem(t, n, v);
                        n++;
                    }
                }

                if (binding.outs == 1 && mi.ReturnType == typeof(void))
                {
                    IntPtr v = Runtime.PyTuple_GetItem(t, 0);
                    Runtime.XIncref(v);
                    Runtime.XDecref(t);
                    return(v);
                }

                return(t);
            }

            return(Converter.ToPython(result, mi.ReturnType));
        }
Esempio n. 30
0
        internal virtual IntPtr Invoke(IntPtr inst, IntPtr args, IntPtr kw, Type type, MethodBase info, MethodInfo[] methodinfo)
        {
            List <Binding> bindings = Bind(inst, args, kw, type, info, methodinfo);
            object         result   = null;
            IntPtr         ts       = IntPtr.Zero;

            if (bindings.Count == 0)
            {
                var value = "No method matches given arguments";
                if (methodinfo != null && methodinfo.Length > 0)
                {
                    value += $" for {methodinfo[0].Name}";
                }
                Exceptions.SetError(Exceptions.TypeError, value);
                return(IntPtr.Zero);
            }

            if (allow_threads)
            {
                ts = PythonEngine.BeginAllowThreads();
            }

            #region COM Binding

            Binding   binding = null;
            Exception ex      = new Exception();

            foreach (Binding bind in bindings)
            {
                if (binding != null)
                {
                    break;
                }

                try
                {
                    result  = bind.info.Invoke(bind.inst, BindingFlags.Default, null, bind.args, null);
                    binding = bind;
                }
                catch (TargetInvocationException e)
                {
                    System.Diagnostics.Debug.WriteLine("TargetInvocationException: " + bind.info.Name + " with " + bind.args.Length + " arguments.");
                    binding = null;
                    ex      = e;
                }
                catch (Exception e)
                {
                    binding = null;
                    ex      = e;
                }
            }


            if (binding == null)
            {
                if (ex.InnerException != null)
                {
                    ex = ex.InnerException;
                }
                if (allow_threads)
                {
                    PythonEngine.EndAllowThreads(ts);
                }
                Exceptions.SetError(ex);

                return(IntPtr.Zero);
            }

            #endregion

            if (allow_threads)
            {
                PythonEngine.EndAllowThreads(ts);
            }

            // If there are out parameters, we return a tuple containing
            // the result followed by the out parameters. If there is only
            // one out parameter and the return type of the method is void,
            // we return the out parameter as the result to Python (for
            // code compatibility with ironpython).

            var mi = (MethodInfo)binding.info;

            if (binding.outs == 1 && mi.ReturnType == typeof(void))
            {
            }

            if (binding.outs > 0)
            {
                ParameterInfo[] pi = mi.GetParameters();
                int             c  = pi.Length;
                var             n  = 0;

                IntPtr t = Runtime.PyTuple_New(binding.outs + 1);
                IntPtr v = Converter.ToPython(result, mi.ReturnType);
                Runtime.PyTuple_SetItem(t, n, v);
                n++;

                for (var i = 0; i < c; i++)
                {
                    Type pt = pi[i].ParameterType;
                    if (pi[i].IsOut || pt.IsByRef)
                    {
                        v = Converter.ToPython(binding.args[i], pt);
                        Runtime.PyTuple_SetItem(t, n, v);
                        n++;
                    }
                }

                if (binding.outs == 1 && mi.ReturnType == typeof(void))
                {
                    v = Runtime.PyTuple_GetItem(t, 1);
                    Runtime.XIncref(v);
                    Runtime.XDecref(t);
                    return(v);
                }

                return(t);
            }

            return(Converter.ToPython(result, mi.ReturnType));
        }