PyTuple_New() private méthode

private PyTuple_New ( int size ) : IntPtr
size int
Résultat IntPtr
Exemple #1
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);
        }
Exemple #2
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
        }
Exemple #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());
            }
        }
Exemple #4
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);
        }
        //====================================================================
        // 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);
        }
Exemple #6
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());
            }
        }
Exemple #7
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 #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 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);
        }
Exemple #9
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));
        }
Exemple #10
0
        private void GetArgs(object[] inargs, CallInfo callInfo, out PyTuple args, out PyDict kwargs)
        {
            if (callInfo == null || callInfo.ArgumentNames.Count == 0)
            {
                GetArgs(inargs, out args, out kwargs);
                return;
            }

            // Support for .net named arguments
            var namedArgumentCount   = callInfo.ArgumentNames.Count;
            var regularArgumentCount = callInfo.ArgumentCount - namedArgumentCount;

            var argTuple = Runtime.PyTuple_New(regularArgumentCount);

            for (int i = 0; i < regularArgumentCount; ++i)
            {
                AddArgument(argTuple, i, inargs[i]);
            }
            args = new PyTuple(argTuple);

            var namedArgs = new object[namedArgumentCount * 2];

            for (int i = 0; i < namedArgumentCount; ++i)
            {
                namedArgs[i * 2]     = callInfo.ArgumentNames[i];
                namedArgs[i * 2 + 1] = inargs[regularArgumentCount + i];
            }
            kwargs = Py.kw(namedArgs);
        }
Exemple #11
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 (var i = 0; i < arg_count; i++)
            {
                AddArgument(argtuple, i, inargs[i]);
            }
            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]);
                }
            }
        }
Exemple #12
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);
        }
Exemple #13
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);
        }
Exemple #14
0
 /// <summary>
 /// PyTuple Constructor
 /// </summary>
 ///
 /// <remarks>
 /// Creates a new empty PyTuple.
 /// </remarks>
 public PyTuple() : base()
 {
     obj = Runtime.PyTuple_New(0);
     if (obj == IntPtr.Zero)
     {
         throw new PythonException();
     }
 }
Exemple #15
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();
            }
        }
Exemple #16
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));
        }
Exemple #17
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);
            }
        }
Exemple #18
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();
                }
            }
        }
Exemple #19
0
            public override ValueType Execute(ValueType arg)
            {
                var module = (IntPtr)arg;
                using (Py.GIL())
                {
                    var test_obj_call = PyRuntime.PyObject_GetAttrString(module, "test_obj_call");
                    PythonException.ThrowIfIsNull(test_obj_call);
                    var args = PyRuntime.PyTuple_New(0);
                    var res = PyRuntime.PyObject_CallObject(test_obj_call, args);
                    PythonException.ThrowIfIsNull(res);

                    PyRuntime.XDecref(args);
                    PyRuntime.XDecref(res);
                }
                return 0;
            }
        /// <summary>
        /// Allows ctor selection to be limited to a single attempt at a
        /// match by providing the MethodBase to use instead of searching
        /// the entire MethodBinder.list (generic ArrayList)
        /// </summary>
        /// <param name="inst"> (possibly null) instance </param>
        /// <param name="args"> PyObject* to the arg tuple </param>
        /// <param name="kw"> PyObject* to the keyword args dict </param>
        /// <param name="info"> The sole ContructorInfo to use or null </param>
        /// <returns> The result of the constructor call with converted params </returns>
        /// <remarks>
        /// 2010-07-24 BC: I added the info parameter to the call to Bind()
        /// Binding binding = this.Bind(inst, args, kw, info);
        /// to take advantage of Bind()'s ability to use a single MethodBase (CI or MI).
        /// </remarks>
        internal object InvokeRaw(IntPtr inst, IntPtr args, IntPtr kw,
                                  MethodBase info)
        {
            Binding binding = this.Bind(inst, args, kw, info);
            Object  result;

            if (binding == null)
            {
                // It is possible for __new__ to be invoked on construction
                // of a Python subclass of a managed class, so args may
                // reflect more args than are required to instantiate the
                // class. So if we cant find a ctor that matches, we'll see
                // if there is a default constructor and, if so, assume that
                // any extra args are intended for the subclass' __init__.

                IntPtr eargs = Runtime.PyTuple_New(0);
                binding = this.Bind(inst, eargs, kw);
                Runtime.Decref(eargs);

                if (binding == null)
                {
                    Exceptions.SetError(Exceptions.TypeError,
                                        "no constructor matches given arguments"
                                        );
                    return(null);
                }
            }

            // Fire the selected ctor and catch errors...
            ConstructorInfo ci = (ConstructorInfo)binding.info;

            // Object construction is presumed to be non-blocking and fast
            // enough that we shouldn't really need to release the GIL.
            try {
                result = ci.Invoke(binding.args);
            }
            catch (Exception e) {
                if (e.InnerException != null)
                {
                    e = e.InnerException;
                }
                Exceptions.SetError(e);
                return(null);
            }
            return(result);
        }
Exemple #21
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]);
                }
            }
        }
Exemple #22
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);
        }
Exemple #23
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);
        }
Exemple #24
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);
        }
Exemple #25
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);
            }
        }
Exemple #26
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);
        }
Exemple #27
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();
                }
            }
        }
Exemple #28
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());
        }
Exemple #29
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);
        }
        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));
        }