示例#1
0
        /// <summary>
        /// Get an object in memory from specified base address.
        /// </summary>
        /// <param name="t">The type of object.</param>
        /// <param name="address">The address.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">t</exception>
        /// <exception cref="System.ArgumentException">
        /// Type can not be abstract!
        /// or
        /// Type must inherit from VirtualObject!
        /// </exception>
        public static IVirtualObject FromAddressSafeCast(Type t, IntPtr address)
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }
            if (!t.IsInterface)
            {
                throw new ArgumentException("Type must be interface!");
            }
            if (t != typeof(IVirtualObject) && !typeof(IVirtualObject).IsAssignableFrom(t))
            {
                throw new ArgumentException("Type must inherit from IVirtualObject!");
            }

            if (address == IntPtr.Zero)
            {
                return(null);
            }

            TypeDescriptor td = null;

            if (Main.Game != null)
            {
                if (!Main.Game.Types.TypesByInterface.TryGetValue(t, out td))
                {
                    td = null;

                    if (t.IsGenericType && !t.IsGenericTypeDefinition)
                    {
                        var t2 = t.GetGenericTypeDefinition();
                        if (!Main.Game.Types.TypesByInterface.TryGetValue(t2, out td))
                        {
                            td = null;
                        }
                    }
                }
            }

            if (td == null)
            {
                return(null);
            }

            VirtualObject mo = null;

            if (td.IsGeneric)
            {
                var ci = td.GetGenericConstructor(t.GenericTypeArguments);
                mo = (VirtualObject)ci.Invoke(new object[0]);
            }
            else
            {
                mo = (VirtualObject)td.ConstructorNonGeneric.Invoke(new object[0]);
            }

            mo.Address = address;

            try
            {
                return(mo.As(t));
            }
            catch (NotSupportedException)
            {
            }

            return(null);
        }