PyTuple_Check() static private méthode

static private PyTuple_Check ( IntPtr ob ) : bool
ob IntPtr
Résultat bool
        //====================================================================
        // 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 #2
0
        //====================================================================
        // Implementation of [] semantics for reflected types. This mainly
        // exists to implement the Array[int] syntax for creating arrays.
        //====================================================================

        public override IntPtr type_subscript(IntPtr ob, IntPtr idx)
        {
            if ((this.type) != typeof(Array))
            {
                return(Exceptions.RaiseTypeError("unsubscriptable object"));
            }

            if (Runtime.PyTuple_Check(idx))
            {
                return(Exceptions.RaiseTypeError("expected single type"));
            }

            ClassBase c = GetManagedObject(idx) as ClassBase;
            Type      t = (c != null) ? c.type : Converter.GetTypeByAlias(idx);

            if (t == null)
            {
                return(Exceptions.RaiseTypeError("type expected"));
            }
            Array a = Array.CreateInstance(t, 0);

            c = ClassManager.GetClass(a.GetType());
            Runtime.Incref(c.pyHandle);
            return(c.pyHandle);
        }
Exemple #3
0
        //===================================================================
        // Return the clr python module (new reference)
        //===================================================================
        public static IntPtr GetCLRModule(IntPtr?fromList = null)
        {
            root.InitializePreload();
#if (PYTHON32 || PYTHON33 || PYTHON34 || PYTHON35)
            // update the module dictionary with the contents of the root dictionary
            root.LoadNames();
            IntPtr py_mod_dict = Runtime.PyModule_GetDict(py_clr_module);
            IntPtr clr_dict    = Runtime._PyObject_GetDictPtr(root.pyHandle); // PyObject**
            clr_dict = (IntPtr)Marshal.PtrToStructure(clr_dict, typeof(IntPtr));
            Runtime.PyDict_Update(py_mod_dict, clr_dict);

            // find any items from the fromlist and get them from the root if they're not
            // aleady in the module dictionary
            if (fromList != null && fromList != IntPtr.Zero)
            {
                if (Runtime.PyTuple_Check(fromList.GetValueOrDefault()))
                {
                    Runtime.Incref(py_mod_dict);
                    using (PyDict mod_dict = new PyDict(py_mod_dict)) {
                        Runtime.Incref(fromList.GetValueOrDefault());
                        using (PyTuple from = new PyTuple(fromList.GetValueOrDefault())) {
                            foreach (PyObject item in from)
                            {
                                if (mod_dict.HasKey(item))
                                {
                                    continue;
                                }

                                string s = item.AsManagedObject(typeof(string)) as string;
                                if (null == s)
                                {
                                    continue;
                                }

                                ManagedType attr = root.GetAttribute(s, true);
                                if (null == attr)
                                {
                                    continue;
                                }

                                Runtime.Incref(attr.pyHandle);
                                using (PyObject obj = new PyObject(attr.pyHandle)) {
                                    mod_dict.SetItem(s, obj);
                                }
                            }
                        }
                    }
                }
            }

            Runtime.Incref(py_clr_module);
            return(py_clr_module);
#else
            Runtime.Incref(root.pyHandle);
            return(root.pyHandle);
#endif
        }
Exemple #4
0
        /// <summary>
        /// Return the clr python module (new reference)
        /// </summary>
        public static unsafe NewReference GetCLRModule(BorrowedReference fromList = default)
        {
            root.InitializePreload();

            // update the module dictionary with the contents of the root dictionary
            root.LoadNames();
            BorrowedReference py_mod_dict = Runtime.PyModule_GetDict(ClrModuleReference);

            using (var clr_dict = Runtime.PyObject_GenericGetDict(root.ObjectReference))
            {
                Runtime.PyDict_Update(py_mod_dict, clr_dict);
            }

            // find any items from the from list and get them from the root if they're not
            // already in the module dictionary
            if (fromList != null)
            {
                if (Runtime.PyTuple_Check(fromList))
                {
                    using var mod_dict = new PyDict(py_mod_dict);
                    using var from     = new PyTuple(fromList);
                    foreach (PyObject item in from)
                    {
                        if (mod_dict.HasKey(item))
                        {
                            continue;
                        }

                        var s = item.AsManagedObject(typeof(string)) as string;
                        if (s == null)
                        {
                            continue;
                        }

                        ManagedType attr = root.GetAttribute(s, true);
                        if (attr == null)
                        {
                            continue;
                        }

                        Runtime.XIncref(attr.pyHandle);
                        using (var obj = new PyObject(attr.pyHandle))
                        {
                            mod_dict.SetItem(s, obj);
                        }
                    }
                }
            }
            Runtime.XIncref(py_clr_module);
            return(NewReference.DangerousFromPointer(py_clr_module));
        }
Exemple #5
0
        /// <summary>
        /// Implementation of [] semantics for reflected types. This exists
        /// both to implement the Array[int] syntax for creating arrays and
        /// to support generic name overload resolution using [].
        /// </summary>
        public override IntPtr type_subscript(IntPtr idx)
        {
            if (!type.Valid)
            {
                return(Exceptions.RaiseTypeError(type.DeletedMessage));
            }

            // If this type is the Array type, the [<type>] means we need to
            // construct and return an array type of the given element type.
            if (type.Value == typeof(Array))
            {
                if (Runtime.PyTuple_Check(idx))
                {
                    return(Exceptions.RaiseTypeError("type expected"));
                }
                var  c = GetManagedObject(idx) as ClassBase;
                Type t = c != null ? c.type.Value : Converter.GetTypeByAlias(idx);
                if (t == null)
                {
                    return(Exceptions.RaiseTypeError("type expected"));
                }
                Type      a = t.MakeArrayType();
                ClassBase o = ClassManager.GetClass(a);
                Runtime.XIncref(o.pyHandle);
                return(o.pyHandle);
            }

            // If there are generics in our namespace with the same base name
            // as the current type, then [<type>] means the caller wants to
            // bind the generic type matching the given type parameters.
            Type[] types = Runtime.PythonArgsToTypeArray(idx);
            if (types == null)
            {
                return(Exceptions.RaiseTypeError("type(s) expected"));
            }

            Type gtype = AssemblyManager.LookupTypes($"{type.Value.FullName}`{types.Length}").FirstOrDefault();

            if (gtype != null)
            {
                var g = ClassManager.GetClass(gtype) as GenericType;
                return(g.type_subscript(idx));
                //Runtime.XIncref(g.pyHandle);
                //return g.pyHandle;
            }
            return(Exceptions.RaiseTypeError("unsubscriptable object"));
        }
Exemple #6
0
        //====================================================================
        // Implementation of [] semantics for reflected types. This exists
        // both to implement the Array[int] syntax for creating arrays and
        // to support generic name overload resolution using [].
        //====================================================================

        public override IntPtr type_subscript(IntPtr idx)
        {
            // If this type is the Array type, the [<type>] means we need to
            // construct and return an array type of the given element type.

            if ((this.type) == typeof(Array))
            {
                if (Runtime.PyTuple_Check(idx))
                {
                    return(Exceptions.RaiseTypeError("type expected"));
                }
                ClassBase c = GetManagedObject(idx) as ClassBase;
                Type      t = (c != null) ? c.type : Converter.GetTypeByAlias(idx);
                if (t == null)
                {
                    return(Exceptions.RaiseTypeError("type expected"));
                }
                Type      a = t.MakeArrayType();
                ClassBase o = ClassManager.GetClass(a);
                Runtime.Incref(o.pyHandle);
                return(o.pyHandle);
            }

            // If there are generics in our namespace with the same base name
            // as the current type, then [<type>] means the caller wants to
            // bind the generic type matching the given type parameters.

            Type[] types = Runtime.PythonArgsToTypeArray(idx);
            if (types == null)
            {
                return(Exceptions.RaiseTypeError("type(s) expected"));
            }

            string gname = this.type.FullName + "`" + types.Length.ToString();
            Type   gtype = AssemblyManager.LookupType(gname);

            if (gtype != null)
            {
                GenericType g = ClassManager.GetClass(gtype) as GenericType;
                return(g.type_subscript(idx));

                /*Runtime.Incref(g.pyHandle);
                 * return g.pyHandle;*/
            }
            return(Exceptions.RaiseTypeError("unsubscriptable object"));
        }
Exemple #7
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 #8
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);
        }
Exemple #9
0
 /// <summary>
 /// IsTupleType Method
 /// </summary>
 ///
 /// <remarks>
 /// Returns true if the given object is a Python tuple.
 /// </remarks>
 public static bool IsTupleType(PyObject value)
 {
     return(Runtime.PyTuple_Check(value.obj));
 }
Exemple #10
0
        /// <summary>
        /// Implements __getitem__ for array types.
        /// </summary>
        public static IntPtr mp_subscript(IntPtr ob, IntPtr idx)
        {
            var    obj      = (CLRObject)GetManagedObject(ob);
            var    items    = obj.inst as Array;
            Type   itemType = obj.inst.GetType().GetElementType();
            int    rank     = items.Rank;
            int    index;
            object value;

            // Note that CLR 1.0 only supports int indexes - methods to
            // support long indices were introduced in 1.1. We could
            // support long indices automatically, but given that long
            // indices are not backward compatible and a relative edge
            // case, we won't bother for now.

            // Single-dimensional arrays are the most common case and are
            // cheaper to deal with than multi-dimensional, so check first.

            if (rank == 1)
            {
                index = Runtime.Interop.PyInt_AsLong(idx);

                if (Exceptions.ErrorOccurred())
                {
                    return(Exceptions.RaiseTypeError("invalid index value"));
                }

                if (index < 0)
                {
                    index = items.Length + index;
                }

                try
                {
                    value = items.GetValue(index);
                }
                catch (IndexOutOfRangeException)
                {
                    Exceptions.SetError(Exceptions.IndexError, "array index out of range");
                    return(IntPtr.Zero);
                }

                return(Converter.ToPython(value, itemType));
            }

            // Multi-dimensional arrays can be indexed a la: list[1, 2, 3].

            if (!Runtime.PyTuple_Check(idx))
            {
                Exceptions.SetError(Exceptions.TypeError, "invalid index value");
                return(IntPtr.Zero);
            }

            int count = Runtime.Interop.PyTuple_Size(idx);

            var args = new int[count];

            for (var i = 0; i < count; i++)
            {
                IntPtr op = Runtime.Interop.PyTuple_GetItem(idx, i);
                index = Runtime.Interop.PyInt_AsLong(op);

                if (Exceptions.ErrorOccurred())
                {
                    return(Exceptions.RaiseTypeError("invalid index value"));
                }

                if (index < 0)
                {
                    index = items.GetLength(i) + index;
                }

                args.SetValue(index, i);
            }

            try
            {
                value = items.GetValue(args);
            }
            catch (IndexOutOfRangeException)
            {
                Exceptions.SetError(Exceptions.IndexError, "array index out of range");
                return(IntPtr.Zero);
            }

            return(Converter.ToPython(value, itemType));
        }
Exemple #11
0
        /// <summary>
        /// Implements __setitem__ for array types.
        /// </summary>
        public static int mp_ass_subscript(IntPtr ob, IntPtr idx, IntPtr v)
        {
            var    obj      = (CLRObject)GetManagedObject(ob);
            var    items    = obj.inst as Array;
            Type   itemType = obj.inst.GetType().GetElementType();
            int    rank     = items.Rank;
            int    index;
            object value;

            if (items.IsReadOnly)
            {
                Exceptions.RaiseTypeError("array is read-only");
                return(-1);
            }

            if (!Converter.ToManaged(v, itemType, out value, true))
            {
                return(-1);
            }

            if (rank == 1)
            {
                index = Runtime.Interop.PyInt_AsLong(idx);

                if (Exceptions.ErrorOccurred())
                {
                    Exceptions.RaiseTypeError("invalid index value");
                    return(-1);
                }

                if (index < 0)
                {
                    index = items.Length + index;
                }

                try
                {
                    items.SetValue(value, index);
                }
                catch (IndexOutOfRangeException)
                {
                    Exceptions.SetError(Exceptions.IndexError, "array index out of range");
                    return(-1);
                }

                return(0);
            }

            if (!Runtime.PyTuple_Check(idx))
            {
                Exceptions.RaiseTypeError("invalid index value");
                return(-1);
            }

            int count = Runtime.Interop.PyTuple_Size(idx);
            var args  = new int[count];

            for (var i = 0; i < count; i++)
            {
                IntPtr op = Runtime.Interop.PyTuple_GetItem(idx, i);
                index = Runtime.Interop.PyInt_AsLong(op);

                if (Exceptions.ErrorOccurred())
                {
                    Exceptions.RaiseTypeError("invalid index value");
                    return(-1);
                }

                if (index < 0)
                {
                    index = items.GetLength(i) + index;
                }

                args.SetValue(index, i);
            }

            try
            {
                items.SetValue(value, args);
            }
            catch (IndexOutOfRangeException)
            {
                Exceptions.SetError(Exceptions.IndexError, "array index out of range");
                return(-1);
            }

            return(0);
        }
Exemple #12
0
        private object?TrueDispatch(object?[] args)
        {
            MethodInfo method = dtype.GetMethod("Invoke");

            ParameterInfo[] pi    = method.GetParameters();
            Type            rtype = method.ReturnType;

            NewReference callResult;

            using (var pyargs = Runtime.PyTuple_New(pi.Length))
            {
                for (var i = 0; i < pi.Length; i++)
                {
                    // Here we own the reference to the Python value, and we
                    // give the ownership to the arg tuple.
                    using var arg = Converter.ToPython(args[i], pi[i].ParameterType);
                    int res = Runtime.PyTuple_SetItem(pyargs.Borrow(), i, arg.StealOrThrow());
                    if (res != 0)
                    {
                        throw PythonException.ThrowLastAsClrException();
                    }
                }

                callResult = Runtime.PyObject_Call(target, pyargs.Borrow(), null);
            }

            if (callResult.IsNull())
            {
                throw PythonException.ThrowLastAsClrException();
            }

            using (callResult)
            {
                BorrowedReference op = callResult.Borrow();
                int byRefCount       = pi.Count(parameterInfo => parameterInfo.ParameterType.IsByRef);
                if (byRefCount > 0)
                {
                    // By symmetry with MethodBinder.Invoke, when there are out
                    // parameters we expect to receive 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 instead receive the out parameter as the result from Python.

                    bool isVoid    = rtype == typeof(void);
                    int  tupleSize = byRefCount + (isVoid ? 0 : 1);
                    if (isVoid && byRefCount == 1)
                    {
                        // The return type is void and there is a single out parameter.
                        for (int i = 0; i < pi.Length; i++)
                        {
                            Type t = pi[i].ParameterType;
                            if (t.IsByRef)
                            {
                                if (!Converter.ToManaged(op, t, out args[i], true))
                                {
                                    Exceptions.RaiseTypeError($"The Python function did not return {t.GetElementType()} (the out parameter type)");
                                    throw PythonException.ThrowLastAsClrException();
                                }
                                break;
                            }
                        }
                        return(null);
                    }
                    else if (Runtime.PyTuple_Check(op) && Runtime.PyTuple_Size(op) == tupleSize)
                    {
                        int index = isVoid ? 0 : 1;
                        for (int i = 0; i < pi.Length; i++)
                        {
                            Type t = pi[i].ParameterType;
                            if (t.IsByRef)
                            {
                                BorrowedReference item = Runtime.PyTuple_GetItem(op, index++);
                                if (!Converter.ToManaged(item, t, out args[i], true))
                                {
                                    Exceptions.RaiseTypeError($"The Python function returned a tuple where element {i} was not {t.GetElementType()} (the out parameter type)");
                                    throw PythonException.ThrowLastAsClrException();
                                }
                            }
                        }
                        if (isVoid)
                        {
                            return(null);
                        }
                        BorrowedReference item0 = Runtime.PyTuple_GetItem(op, 0);
                        if (!Converter.ToManaged(item0, rtype, out object?result0, true))
                        {
                            Exceptions.RaiseTypeError($"The Python function returned a tuple where element 0 was not {rtype} (the return type)");
                            throw PythonException.ThrowLastAsClrException();
                        }
                        return(result0);
                    }
                    else
                    {
                        string tpName = Runtime.PyObject_GetTypeName(op);
                        if (Runtime.PyTuple_Check(op))
                        {
                            tpName += $" of size {Runtime.PyTuple_Size(op)}";
                        }
                        StringBuilder sb = new StringBuilder();
                        if (!isVoid)
                        {
                            sb.Append(rtype.FullName);
                        }
                        for (int i = 0; i < pi.Length; i++)
                        {
                            Type t = pi[i].ParameterType;
                            if (t.IsByRef)
                            {
                                if (sb.Length > 0)
                                {
                                    sb.Append(",");
                                }
                                sb.Append(t.GetElementType().FullName);
                            }
                        }
                        string returnValueString = isVoid ? "" : "the return value and ";
                        Exceptions.RaiseTypeError($"Expected a tuple ({sb}) of {returnValueString}the values for out and ref parameters, got {tpName}.");
                        throw PythonException.ThrowLastAsClrException();
                    }
                }

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

                if (!Converter.ToManaged(op, rtype, out object?result, true))
                {
                    throw PythonException.ThrowLastAsClrException();
                }

                return(result);
            }
        }
Exemple #13
0
        internal static MethodInfo MatchByTypeSig(MethodInfo[] msig,
                                                  IntPtr psig)
        {
            IntPtr args = psig;
            bool   free = false;

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

            int        plen  = Runtime.PyTuple_Size(args);
            MethodInfo match = null;

            // XXX: what about out args, etc.?

            for (int i = 0; i < msig.Length; i++)
            {
                ParameterInfo[] pi = msig[i].GetParameters();
                if (pi.Length != plen)
                {
                    continue;
                }
                bool matched = true;
                for (int n = 0; n < pi.Length; n++)
                {
                    IntPtr p = Runtime.PyTuple_GetItem(args, n);
                    if (p == IntPtr.Zero)
                    {
                        Exceptions.Clear();
                        break;
                    }
                    ClassBase c = ManagedType.GetManagedObject(p) as ClassBase;
                    Type      t = (c != null) ? c.type :
                                  Converter.GetTypeByAlias(p);

                    if (t == null)
                    {
                        break;
                    }
                    if (t != pi[n].ParameterType)
                    {
                        matched = false;
                        break;
                    }
                }
                if (matched)
                {
                    match = msig[i];
                    break;
                }
            }

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

            return(match);
        }