Exemple #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TypeResults"/> class.
 /// </summary>
 /// <param name="methodReference">
 /// The reflected information on the final method produced by the compiler.
 /// </param>
 /// <param name="compiledType">
 /// The results of the programmatically-accessed compilation of the containing type.
 /// </param>
 protected internal MethodResults(MethodInfo methodReference, TypeResults compiledType)
 {
     typeResults = compiledType;
     method = methodReference;
     Instance = typeResults.Instantiate();
     FastInvoke = Hack.GetMethodInvoker(method);
 }
Exemple #2
0
        public CallInfo(string methodId,MethodBase method, IList interceptors, FastInvokeHandler handler)
        {
			MethodId = methodId;
            Method = method;
            Interceptors = interceptors;
            Handler = handler;
        }
Exemple #3
0
    /// <summary>
    /// 获取web函数
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public void Load(Type type)
    {
        Dictionary <string, FastInvokeHandler> dic = new Dictionary <string, FastInvokeHandler>(StringComparer.OrdinalIgnoreCase);

        MethodInfo[] methods = type.GetMethods(FastValueGetSet.AllBindingFlags);
        foreach (MethodInfo info in methods)
        {
            string    key = GetMethodInfoKey(info);
            WebMethod att = info.GetCustomAttribute(typeof(WebMethod)) as WebMethod;
            if (att != null)
            {
                FastInvokeHandler handle = FastInvoke.GetMethodInvoker(info);
                dic[key] = handle;
            }
        }
        _dicMethods = dic;
    }
Exemple #4
0
        public static void Awake <A, B, C>(Object obj, A a, B b, C c)
        {
            Type type = obj.GetType();
            FastInvokeHandler awakeInvoke = FastInvokeCache.GetMethod(type, "Awake", typeof(A), typeof(B), typeof(C));

            if (awakeInvoke != null)
            {
                try
                {
                    awakeInvoke(obj, new object[] { a, b, c });
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
Exemple #5
0
        public static void Destroy(Object obj)
        {
            Type type = obj.GetType();
            FastInvokeHandler destoryInvoke = FastInvokeCache.GetMethod(type, "Destroy");

            if (destoryInvoke != null)
            {
                try
                {
                    destoryInvoke(obj, null);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
        /// <summary>
        /// Initialize a new instance of <see cref="PropertyDescriptor"/>.
        /// </summary>
        /// <param name="propertyInfo">The <see cref="PropertyInfo"/> to wrap.</param>
        /// <param name="typeDescriptor">The <see cref="Reflection.TypeDescriptor"/> this <see cref="PropertyDescriptor"/> belongs to.</param>
        /// <param name="getMethodInfo">The get <see cref="MethodInfo"/> for the <see cref="PropertyInfo"/> being wrapped.</param>
        /// <exception cref="NullReferenceException"><paramref name="propertyInfo"/> is null.</exception>
        internal PropertyDescriptor(TypeDescriptor typeDescriptor, PropertyInfo propertyInfo, MethodInfo getMethodInfo)
            : base(getMethodInfo.ReturnType, propertyInfo.Name)
        {
            if (propertyInfo.PropertyType.IsGenericParameter)
            {
                throw new ArgumentException("propertyInfo cannot be a genetic type.", "propertyInfo");
            }
            TypeDescriptor = typeDescriptor;
            IsStatic = getMethodInfo.IsStatic;
            IsVirtual = getMethodInfo.IsVirtual;
#if(WindowsCE || SILVERLIGHT)
            this.getMethodInfo = getMethodInfo;
#else
            invoker = MethodInvokerCreator.GetMethodInvoker(getMethodInfo);
#endif
			AddRulesForPropertyInfo(propertyInfo);
        }
Exemple #7
0
        public static void Awake(Object obj)
        {
            Type type = obj.GetType();
            FastInvokeHandler awakeInvoke = FastInvokeCache.GetMethod(type, "Awake");

            if (awakeInvoke != null)
            {
                try
                {
                    awakeInvoke(obj, null);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }
        }
Exemple #8
0
        /// <summary>
        /// 通过字符串的方式来执行方法
        /// </summary>
        /// <param name="obj">方法所在对象</param>
        /// <param name="name">方法名称</param>
        /// <param name="values">方法对应的参数值</param>
        /// <returns></returns>
        protected object RunMethod(object obj, string name, params object[] values)
        {
            Type       type   = obj.GetType();
            MethodInfo method = type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public);

            if (method == null)
            {
                return(null);
            }
            try
            {
                FastInvokeHandler handler = DynamicCalls.GetMethodInvoker(method);
                return(handler.Invoke(obj, values));
            }
            catch
            {
                return(null);
            }
        }
Exemple #9
0
        public static object Try <T>(T target, string methodName, object[] parameters)
            where T : class
        {
            try
            {
                Type       t          = typeof(T);
                MethodInfo methodInfo = t.GetMethod(methodName,
                                                    BindingFlags.NonPublic | BindingFlags.Instance);
                FastInvokeHandler fastInvoker = GetMethodInvoker(methodInfo);


                // bug: »á±¨´í
                return(fastInvoker(target, parameters));
            }
            catch
            {
                return(null);
            }
        }
Exemple #10
0
        public static FastInvokeHandler Get(MethodInfo methodInfo)
        {
            FastInvokeHandler invc     = null;
            string            cacheKey = GenerateMethodKey(methodInfo);

            if (!SDict.TryGetValue(cacheKey, out invc))
            {
                lock (SSyncHelper)
                {
                    if (!SDict.TryGetValue(GenerateMethodKey(methodInfo), out invc))
                    {
                        invc = GetImpl(methodInfo);
                        SDict.Add(cacheKey, invc);
                    }
                }
            }

            return(invc);
        }
Exemple #11
0
        static void Main(string[] args)
        {
            Type       t          = typeof(Person);
            MethodInfo methodInfo = t.GetMethod("Say");
            Person     person     = new Person();
            string     word       = "hello";
            Person     p          = null;

            object[] param = new object[] { word, p, 3 };

            Stopwatch watch = new Stopwatch();

            watch.Start();
            for (int i = 0; i < 1000000; i++)
            {
                methodInfo.Invoke(person, param);
            }
            watch.Stop();
            Console.WriteLine("1000000 times invoked by Reflection: " + watch.ElapsedMilliseconds + "ms");

            Stopwatch         watch1      = new Stopwatch();
            FastInvokeHandler fastInvoker = GetMethodInvoker(methodInfo);

            watch1.Start();
            for (int i = 0; i < 1000000; i++)
            {
                fastInvoker(person, param);
            }
            watch1.Stop();
            Console.WriteLine("1000000 times invoked by FastInvoke: " + watch1.ElapsedMilliseconds + "ms");

            Stopwatch watch2 = new Stopwatch();

            watch2.Start();
            for (int i = 0; i < 1000000; i++)
            {
                person.Say(ref word, out p, 3);
            }
            watch2.Stop();
            Console.WriteLine("1000000 times invoked by DirectCall: " + watch2.ElapsedMilliseconds + "ms");

            Console.ReadLine();
        }
Exemple #12
0
        public static object Invoke(object instance, string methodName, object[] paramters)
        {
            var               type          = instance.GetType();
            string            classFullName = instance.GetType().ToString();
            string            key           = classFullName + methodName;
            FastInvokeHandler handler       = null;
            bool              existKey      = true;

            lock (_keyFastInvokeHandlerLock){
                if (_keyFastInvokeHandler.ContainsKey(key))
                {
                    handler = _keyFastInvokeHandler[key];
                }
                else
                {
                    existKey = false;
                }
            }
            if (existKey == false)
            {
                var methodInfo = type.GetMethod(methodName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                if (methodInfo == null)
                {
                    return(null);
                }
                handler = GetMethodInvoker(methodInfo);
                lock (_keyFastInvokeHandlerLock){
                    _keyFastInvokeHandler[key] = handler;
                }
            }
            try {
                return(handler.Invoke(instance, paramters));
            } catch (Exception ex) {
                StringBuilder msg = new StringBuilder();
                msg.AppendLine("调用方法:" + classFullName + "-->" + methodName);
                msg.AppendLine("异常信息:" + ex.Message);
                msg.AppendLine("StackTrace:" + ex.StackTrace);
                string info = msg.ToString();
                Moon.Orm.Util.LogUtil.Error(info);
                throw new Exception(info);
            }
        }
        private static FastInvokeHandler GetAdapter(Type sourceType, Type destinationType, bool hasDestination = false)
        {
            var key = sourceType.FullName + destinationType.FullName;

            if (_cache.ContainsKey(key))
            {
                return(_cache[key]);
            }
            lock (_cache)
            {
                if (_cache.ContainsKey(key))
                {
                    return(_cache[key]);
                }

                var arguments = hasDestination ? new[] { sourceType, destinationType } : new[] { sourceType };

                FastInvokeHandler invoker = null;

                if (ReflectionUtils.IsPrimitive(sourceType) && ReflectionUtils.IsPrimitive(destinationType))
                {
                    invoker = FastInvoker.GetMethodInvoker(typeof(PrimitiveAdapter <,>)
                                                           .MakeGenericType(sourceType, destinationType).GetMethod("Adapt", arguments));
                }
                else if (ReflectionUtils.IsCollection(sourceType) && ReflectionUtils.IsCollection(destinationType))
                {
                    invoker = FastInvoker.GetMethodInvoker(typeof(CollectionAdapter <, ,>)
                                                           .MakeGenericType(sourceType, ReflectionUtils.ExtractElementType(destinationType),
                                                                            destinationType).GetMethod("Adapt", arguments));
                }
                else
                {
                    invoker = FastInvoker.GetMethodInvoker(typeof(ClassAdapter <,>)
                                                           .MakeGenericType(sourceType, destinationType).GetMethod("Adapt", arguments));
                }

                _cache.Add(key, invoker);
                return(invoker);
            }
        }
Exemple #14
0
                protected FastInvokeHandler GetMethod()
                {
                    Type GetCorrectType(Type inter)
                    {
                        var typeDef = inter.GetGenericTypeDefinition();

                        if (typeDef == typeof(IReadModel <,>) || typeDef == typeof(ISpecificationCommandHandler <>))
                        {
                            return(inter);
                        }
                        return(inter.GetInterfaces().Single());
                    }

                    if (_methodInfo != null)
                    {
                        return(_methodInfo);
                    }

                    var interfaceMapping = _targetType.GetInterfaceMap(GetCorrectType(_targetInterface));

                    _methodInfo = GetMethodInvoker(interfaceMapping.InterfaceMethods.Single(m => !m.Name.StartsWith("Get")));
                    return(_methodInfo);
                }
Exemple #15
0
        private void LoadFrom(Type type, MethodInfo method, RouteAttribute attrib)
        {
            RouteType    = type;
            HttpMethod   = attrib.Method;
            Pattern      = attrib.Pattern;
            MethodParams = method.GetParameters();

            Filters.AddRange(type.GetCustomAttributes <FilterAttribute>());
            Filters.AddRange(method.GetCustomAttributes <FilterAttribute>());

            var transformerAttrib = method.GetCustomAttribute <TransformerAttribute>() ?? type.GetCustomAttribute <TransformerAttribute>();

            if (transformerAttrib != null)
            {
                BodyTransformer = transformerAttrib.Transformer;
            }

            _constructor = type.BindConstructor();

            _contextSetDelegate = type.BindSetProperty(p => p.PropertyType == typeof(HttpListenerContext));

            _delegate = method.BindFastInvoker();
        }
Exemple #16
0
        public CorruptionCore(ModContentPack mod)
        {
            // ITab_Pawn_Soul - checkboxes to allow praying and show prayers
            var type = AccessTools.TypeByName("Corruption.Core.Soul.ITab_Pawn_Soul");

            pawnSoulITabSoulToShowGetter = MethodInvoker.GetHandler(AccessTools.PropertyGetter(type, "SoulToShow"));
            MP.RegisterSyncMethod(typeof(CorruptionCore), nameof(SyncFavourValue));
            MpCompat.harmony.Patch(AccessTools.Method(type, "FillTab"),
                                   prefix: new HarmonyMethod(typeof(CorruptionCore), nameof(PreFillTab)),
                                   postfix: new HarmonyMethod(typeof(CorruptionCore), nameof(PostFillTab)));

            type = AccessTools.TypeByName("Corruption.Core.Soul.CompSoul");
            compSoulFavourTrackerField = AccessTools.FieldRefAccess <object>(type, "FavourTracker");
            compSoulPrayerTrackerField = AccessTools.FieldRefAccess <object>(type, "PrayerTracker");

            type = AccessTools.TypeByName("Corruption.Core.Dialog_SetPawnPantheon");
            setPawnPantheonDialogConstructor = AccessTools.DeclaredConstructor(type);
            setPawnPantheonDialogSoulField   = AccessTools.FieldRefAccess <ThingComp>(type, "soul");
            MP.RegisterSyncMethod(type, "SelectionChanged");
            MP.RegisterSyncWorker <object>(SyncDialogSetPawnPantheon, type);

            type = AccessTools.TypeByName("Corruption.Core.Soul.Soul_FavourTracker");
            soulFavourTrackerFavoursField = AccessTools.FieldRefAccess <IList>(type, "Favours");

            type = AccessTools.TypeByName("Corruption.Core.Gods.Pawn_PrayerTracker");
            prayerTrackerCompSoulField    = AccessTools.FieldRefAccess <ThingComp>(type, "compSoul");
            prayerTrackerAllowPrayingSync = MP.RegisterSyncField(type, "AllowPraying");
            prayerTrackerShowPrayerSync   = MP.RegisterSyncField(type, "ShowPrayer");
            MP.RegisterSyncWorker <object>(SyncPawnPrayerTracker, type);
            MpCompat.harmony.Patch(AccessTools.Method(type, "AdvancePrayer"),
                                   prefix: new HarmonyMethod(typeof(CorruptionCore), nameof(PreAdvancePrayer)),
                                   postfix: new HarmonyMethod(typeof(CorruptionCore), nameof(PostAdvancePrayer)));

            type = AccessTools.TypeByName("Corruption.Core.Soul.FavourProgress");
            favourProgressFavourValueField = AccessTools.FieldRefAccess <float>(type, "favourValue");
        }
Exemple #17
0
        public SmartStockpileCreation(ModContentPack mod)
        {
            // Create Stockpile from Thing
            {
                designatorType = AccessTools.TypeByName("SmartStockpileCreation.RimObjs.SmartStockpile.SmartStockpileDesignator");

                allowedThingsGetter        = MethodInvoker.GetHandler(AccessTools.PropertyGetter(designatorType, "AllowedThings"));
                specialThingFilterDefLabel = AccessTools.FieldRefAccess <SpecialThingFilterDef>(designatorType, "_specialThingFilterDef");
                priorityLabel = AccessTools.FieldRefAccess <StoragePriority>(designatorType, "_priority");
                contentsLabel = AccessTools.FieldRefAccess <string>(designatorType, "_stockpileContentsLabel");

                MP.RegisterSyncWorker <Designator_ZoneAddStockpile>(SmartStockpileDesignatorWorker, designatorType);
            }

            // Reallow Thing in Stockpile
            {
                reallowGizmoType = AccessTools.TypeByName("SmartStockpileCreation.RimObjs.DisallowInStockpile.ReallowInStockpileGizmo");

                thingDefLabel      = AccessTools.FieldRefAccess <ThingDef>(reallowGizmoType, "_thingDef");
                zoneStockpileLabel = AccessTools.FieldRefAccess <Zone_Stockpile>(reallowGizmoType, "_zoneStockpile");
                categoryLabel      = AccessTools.FieldRefAccess <ThingCategoryDef>(reallowGizmoType, "_category");

                MP.RegisterSyncMethod(AccessTools.Method(reallowGizmoType, "ProcessInput")).SetContext(SyncContext.MapSelected);
                MP.RegisterSyncWorker <Command>(ReallowInStockpileGizmoWorker, reallowGizmoType);
            }

            // Disallow Thing in Stockpile
            {
                disallowGizmoType = AccessTools.TypeByName("SmartStockpileCreation.RimObjs.DisallowInStockpile.RemoveFromStockpileGizmo");

                thingLabel = AccessTools.FieldRefAccess <Thing>(disallowGizmoType, "_thing");

                MP.RegisterSyncMethod(AccessTools.Method(disallowGizmoType, "Process")).SetContext(SyncContext.MapSelected);
                MP.RegisterSyncWorker <Command>(RemoveFromStockpileGizmoWorker, disallowGizmoType);
            }
        }
Exemple #18
0
 public CallInfo(string methodId, MethodBase method, IList interceptors, InvocationParameterInfo[] invocationParameterInfos, FastInvokeHandler handler)
 {
     MethodId                 = methodId;
     Method                   = method;
     Interceptors             = interceptors;
     InvocationParameterInfos = invocationParameterInfos;
     Handler                  = handler;
 }
Exemple #19
0
 public SpawnDroneAction()
 {
     _spawnDrone = MethodInvoker.GetHandler(AccessTools.Method(typeof(MyPirateAntennas), "SpawnDrone", new [] { typeof(MyRadioAntenna), typeof(long), typeof(Vector3D), typeof(MySpawnGroupDefinition), typeof(Vector3), typeof(Vector3) }));
 }
        private static void BuildAttackSequenceGetClusteredHits()
        {
            var mi = AccessTools.Method(typeof(AttackDirector.AttackSequence), "GetClusteredHits");

            AttackSequenceGetClusteredHits = MethodInvoker.GetHandler(mi);
        }
Exemple #21
0
 public InvokeInfo(long id, FastInvokeHandler invoke)
 {
     this.id     = id;
     this.invoke = invoke;
 }
Exemple #22
0
        /// <summary>
        /// 运行该函数
        /// </summary>
        /// <param name="methodName">函数名</param>
        /// <param name="args">参数</param>
        /// <returns></returns>
        public object Invoke(string methodName, params object[] args)
        {
            FastInvokeHandler fhandle = FastValueGetSet.GetCustomerMethodInfo(_classHandle.ClassType, methodName, GetParamTypes(args));

            return(fhandle.Invoke(_instance, args));
        }
Exemple #23
0
        /// <summary>
        /// 快速调用方法
        /// </summary>
        /// <param name="method"></param>
        /// <returns></returns>
        public static FastInvokeHandler GetFastMethodInvoke(MethodInfo method)
        {
            FastInvokeHandler invoke = DynamicCalls.GetMethodInvoker(method);

            return(invoke);
        }
Exemple #24
0
 public PropertyAccessor(string Property)
 {
     getMethodHandler = BasePropertyAccessor.GetPropertyInvoker(typeof(TargetType), Property);
     setMethodHandler = BasePropertyAccessor.SetPropertyInvoker(typeof(TargetType), typeof(TargetType).GetProperty(Property));
 }
Exemple #25
0
 public StaticFastInvokeHandler(Type classType, FastInvokeHandler invoker)
 {
     this.classType = classType;
     this.invoker   = invoker;
 }
		/// <inheritdoc />
        public override bool Validate(object targetObjectValue, object targetMemberValue, object context, InfoDescriptor infoDescriptor)
        {
            if (targetMemberValue != null)
			{
#if(WindowsCE || SILVERLIGHT)
				if (propertyToCompareMethodInfo == null)
                {
                    var propertyInfo = targetObjectValue.GetType().GetProperty(PropertyToCompare, TypeDescriptor.PropertyFlags);
                    if (propertyInfo == null)
                    {
                        throw new InvalidOperationException(string.Format("Could not find the property '{0}'", PropertyToCompare));
                    }
                    propertyToCompareMethodInfo = propertyInfo.GetGetMethod(true);
                }
               var propertyToCompareValue = propertyToCompareMethodInfo.Invoke(targetObjectValue, null);
#else
				if (propertyToCompareHandler == null)
                {
                    var propertyInfo = targetObjectValue.GetType().GetProperty(PropertyToCompare, TypeDescriptor.PropertyFlags);
                    if (propertyInfo == null)
                    {
                        throw new InvalidOperationException(string.Format("Could not find the property '{0}'", PropertyToCompare));
                    }
                    var getMethodInfo = propertyInfo.GetGetMethod(true);

                    propertyToCompareHandler = MethodInvokerCreator.GetMethodInvoker(getMethodInfo);
                }
                var propertyToCompareValue = propertyToCompareHandler(targetObjectValue);
#endif

                if ((propertyToCompareValue != null) && !CompareValidationHelper.Compare(targetMemberValue, propertyToCompareValue, CompareOperator))
                {
                    return false;
                }
            }
            return true;
        }
 public SystemMetaData(FastInvokeHandler fastInvokeHandler, Type[] parameterTypes, Type[] componentParameterTypes)
 {
     FastInvokeHandler       = fastInvokeHandler;
     ParameterTypes          = parameterTypes;
     ComponentParameterTypes = componentParameterTypes;
 }
 ///
 public ReflectionAccessor(MethodInfo getMethod, MethodInfo setMethod)
 {
     string name = null;
     if (getMethod != null)
     {
         type = getMethod.ReturnType;
         name = getMethod.DeclaringType.FullName + "." + getMethod.Name;
         if (cacheHandlers.Contains(name))
             getHandler = (FastInvokeHandler)cacheHandlers[name];
         else
         {
             getHandler = GetMethodInvoker(getMethod);
             cacheHandlers[name] = getHandler;
         }
     }
     if (setMethod != null)
     {
         name = setMethod.DeclaringType.FullName + "." + setMethod.Name;
         if (cacheHandlers.Contains(name))
             setHandler = (FastInvokeHandler)cacheHandlers[name];
         else
         {
             setHandler = GetMethodInvoker(setMethod);
             cacheHandlers[name] = setHandler;
         }
     }
 }
Exemple #29
0
 static object InvokeMethod(FastInvokeHandler invoke, object target, params object[] paramters)
 {
     return(invoke(target, paramters));
 }
        public static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo)
        {
            // generates a dynamic method to generate a FastInvokeHandler delegate
            DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object[]) }, methodInfo.DeclaringType.Module);

            ILGenerator ilGenerator = dynamicMethod.GetILGenerator();

            ParameterInfo[] parameters = methodInfo.GetParameters();

            Type[] paramTypes = new Type[parameters.Length];

            // copies the parameter types to an array
            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (parameters[i].ParameterType.IsByRef)
                {
                    paramTypes[i] = parameters[i].ParameterType.GetElementType();
                }
                else
                {
                    paramTypes[i] = parameters[i].ParameterType;
                }
            }

            LocalBuilder[] locals = new LocalBuilder[paramTypes.Length];

            // generates a local variable for each parameter
            for (int i = 0; i < paramTypes.Length; i++)
            {
                locals[i] = ilGenerator.DeclareLocal(paramTypes[i], true);
            }

            // creates code to copy the parameters to the local variables
            for (int i = 0; i < paramTypes.Length; i++)
            {
                ilGenerator.Emit(OpCodes.Ldarg_1);
                EmitFastInt(ilGenerator, i);
                ilGenerator.Emit(OpCodes.Ldelem_Ref);
                EmitCastToReference(ilGenerator, paramTypes[i]);
                ilGenerator.Emit(OpCodes.Stloc, locals[i]);
            }

            if (!methodInfo.IsStatic)
            {
                // loads the object into the stack
                ilGenerator.Emit(OpCodes.Ldarg_0);
            }

            // loads the parameters copied to the local variables into the stack
            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (parameters[i].ParameterType.IsByRef)
                {
                    ilGenerator.Emit(OpCodes.Ldloca_S, locals[i]);
                }
                else
                {
                    ilGenerator.Emit(OpCodes.Ldloc, locals[i]);
                }
            }

            // calls the method
            if (!methodInfo.IsStatic)
            {
                ilGenerator.EmitCall(OpCodes.Callvirt, methodInfo, null);
            }
            else
            {
                ilGenerator.EmitCall(OpCodes.Call, methodInfo, null);
            }

            // creates code for handling the return value
            if (methodInfo.ReturnType == typeof(void))
            {
                ilGenerator.Emit(OpCodes.Ldnull);
            }
            else
            {
                EmitBoxIfNeeded(ilGenerator, methodInfo.ReturnType);
            }

            // iterates through the parameters updating the parameters passed by ref
            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (parameters[i].ParameterType.IsByRef)
                {
                    ilGenerator.Emit(OpCodes.Ldarg_1);
                    EmitFastInt(ilGenerator, i);
                    ilGenerator.Emit(OpCodes.Ldloc, locals[i]);
                    if (locals[i].LocalType.IsValueType)
                    {
                        ilGenerator.Emit(OpCodes.Box, locals[i].LocalType);
                    }
                    ilGenerator.Emit(OpCodes.Stelem_Ref);
                }
            }

            // returns the value to the caller
            ilGenerator.Emit(OpCodes.Ret);

            // converts the DynamicMethod to a FastInvokeHandler delegate to call to the method
            FastInvokeHandler invoker = (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler));

            return(invoker);
        }
Exemple #31
0
 public PropertyAccessor(PropertyInfo Property)
 {
     getMethodHandler = BasePropertyAccessor.GetPropertyInvoker(typeof(TargetType), Property.Name);
     setMethodHandler = BasePropertyAccessor.SetPropertyInvoker(typeof(TargetType), Property);
 }
Exemple #32
0
        /// <summary>
        /// 获取方法快速调用委托
        /// </summary>
        /// <param name="methodInfo">方法对象</param>
        /// <returns></returns>
        public static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo)
        {
            if (methodInfo == null)
            {
                return(null);
            }

            if (!invokeCache.ContainsKey(methodInfo))
            {
                lock (synLock)
                {
                    if (!invokeCache.ContainsKey(methodInfo))
                    {
                        DynamicMethod dynamicMethod = new DynamicMethod(string.Empty,
                                                                        typeof(object), new Type[] { typeof(object),
                                                                                                     typeof(object[]) },
                                                                        methodInfo.DeclaringType.Module);
                        ILGenerator     il         = dynamicMethod.GetILGenerator();
                        ParameterInfo[] ps         = methodInfo.GetParameters();
                        Type[]          paramTypes = new Type[ps.Length];
                        for (int i = 0; i < paramTypes.Length; i++)
                        {
                            paramTypes[i] = ps[i].ParameterType;
                        }
                        LocalBuilder[] locals = new LocalBuilder[paramTypes.Length];
                        for (int i = 0; i < paramTypes.Length; i++)
                        {
                            locals[i] = il.DeclareLocal(paramTypes[i]);
                        }
                        for (int i = 0; i < paramTypes.Length; i++)
                        {
                            il.Emit(OpCodes.Ldarg_1);
                            EmitFastInt(il, i);
                            il.Emit(OpCodes.Ldelem_Ref);
                            EmitCastToReference(il, paramTypes[i]);
                            il.Emit(OpCodes.Stloc, locals[i]);
                        }
                        il.Emit(OpCodes.Ldarg_0);
                        for (int i = 0; i < paramTypes.Length; i++)
                        {
                            il.Emit(OpCodes.Ldloc, locals[i]);
                        }
                        il.EmitCall(OpCodes.Call, methodInfo, null);
                        if (methodInfo.ReturnType == typeof(void))
                        {
                            il.Emit(OpCodes.Ldnull);
                        }
                        else
                        {
                            EmitBoxIfNeeded(il, methodInfo.ReturnType);
                        }
                        il.Emit(OpCodes.Ret);
                        FastInvokeHandler invoder =
                            (FastInvokeHandler)dynamicMethod.CreateDelegate(
                                typeof(FastInvokeHandler));

                        invokeCache.Add(methodInfo, invoder);

                        return(invoder);
                    }
                }
            }

            return(invokeCache[methodInfo]);
        }
Exemple #33
0
        private void button1_Click(object sender, EventArgs e)
        {
            int    loopCount    = 10000;
            string AssemblyName = "TF.Runsafty.bll.Plan";
            string TypeName     = "Plan.LCTrainPlan";
            string MethodName   = "Delete";
            string data         = "{\"strTrainPlanGUID\":\"d\"}";

            System.Diagnostics.Stopwatch watch = new Stopwatch();
            watch.Start();
            Assembly apiASM  = Assembly.Load(AssemblyName);
            Type     apiType = apiASM.GetType("TF.RunSafty." + TypeName, true, true);
            //创建实例
            object     apiObject = Activator.CreateInstance(apiType, true);
            MethodInfo mi;
            string     strMethodName = MethodName;

            object[] args     = new object[] { data };
            Type[]   prmTypes = new Type[] { typeof(string) };
            for (int i = 0; i < loopCount; i++)
            {
                //从程序集获取类型

                //获取方法,方法的参数都只有一个,类型是string,加上prmTypes是避免有函数重构的情况
                mi = apiType.GetMethod(strMethodName, BindingFlags.ExactBinding | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, prmTypes, null);
                //FastInvokeHandler fastInvoker = GetMethodInvoker(mi);

                //调用实例的方法,获取返回值
                object mOut = mi.Invoke(apiObject, args);
            }
            watch.Stop();
            long myUseTime = watch.ElapsedMilliseconds;

            this.listBox1.Items.Add(string.Format("调用反射用时:{0} ms", myUseTime));
            this.listBox1.Refresh();
            watch.Reset();
            watch.Start();

            apiType = typeof(TF.RunSafty.Plan.LCTrainPlan);
            //创建实例
            //object apiObject = Activator.CreateInstance(apiType, true);
            apiObject = new TF.RunSafty.Plan.LCTrainPlan();
            //获取方法,方法的参数都只有一个,类型是string,加上prmTypes是避免有函数重构的情况

            mi = apiType.GetMethod(strMethodName, BindingFlags.ExactBinding | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public, null, prmTypes, null);

            for (int i = 0; i < loopCount; i++)
            {
                //从程序集获取类型

                FastInvokeHandler fastInvoker = GetMethodInvoker(mi);

                //调用实例的方法,获取返回值
                object mOut = fastInvoker(apiObject, args);
            }
            watch.Stop();
            myUseTime = watch.ElapsedMilliseconds;
            this.listBox1.Items.Add(string.Format("调用动态方法用时:{0} ms", myUseTime));
            this.listBox1.Refresh();
            watch.Reset();
            watch.Start();
            TF.RunSafty.Plan.LCTrainPlan lcPlan = null;
            for (int i = 0; i < loopCount; i++)
            {
                lcPlan = new LCTrainPlan();
                lcPlan.Delete(data);
            }
            watch.Stop();
            myUseTime = watch.ElapsedMilliseconds;
            this.listBox1.Items.Add(string.Format("调用实例方法用时:{0} ms", myUseTime));
        }
 static object InvokeMethod(FastInvokeHandler invoke, object target, params object[] paramters)
 {
     return invoke(null, paramters);
 }
Exemple #35
0
 public MethodInvoker(MethodInfo Method)
 {
     methodHandler = BaseMethodInvoker.GetMethodInvoker(Method);
 }
Exemple #36
0
        /// <summary>
        /// 获取方法执行代理
        /// </summary>
        /// <param name="methodInfo"></param>
        /// <returns></returns>
        public static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo)
        {
            DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, typeof(object), new Type[] { typeof(object), typeof(object[]) }, methodInfo.DeclaringType.Module);
            ILGenerator   il            = dynamicMethod.GetILGenerator();

            ParameterInfo[] ps         = methodInfo.GetParameters();
            Type[]          paramTypes = new Type[ps.Length];
            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (ps[i].ParameterType.IsByRef)
                {
                    paramTypes[i] = ps[i].ParameterType.GetElementType();
                }
                else
                {
                    paramTypes[i] = ps[i].ParameterType;
                }
            }
            LocalBuilder[] locals = new LocalBuilder[paramTypes.Length];

            for (int i = 0; i < paramTypes.Length; i++)
            {
                locals[i] = il.DeclareLocal(paramTypes[i], true);
            }
            for (int i = 0; i < paramTypes.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_1);
                EmitFastInt(il, i);
                il.Emit(OpCodes.Ldelem_Ref);
                EmitCastToReference(il, paramTypes[i]);
                il.Emit(OpCodes.Stloc, locals[i]);
            }
            if (!methodInfo.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }
            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (ps[i].ParameterType.IsByRef)
                {
                    il.Emit(OpCodes.Ldloca_S, locals[i]);
                }
                else
                {
                    il.Emit(OpCodes.Ldloc, locals[i]);
                }
            }
            if (methodInfo.IsStatic)
            {
                il.EmitCall(OpCodes.Call, methodInfo, null);
            }
            else
            {
                il.EmitCall(OpCodes.Callvirt, methodInfo, null);
            }
            if (methodInfo.ReturnType == typeof(void))
            {
                il.Emit(OpCodes.Ldnull);
            }
            else
            {
                EmitBoxIfNeeded(il, methodInfo.ReturnType);
            }

            for (int i = 0; i < paramTypes.Length; i++)
            {
                if (ps[i].ParameterType.IsByRef)
                {
                    il.Emit(OpCodes.Ldarg_1);
                    EmitFastInt(il, i);
                    il.Emit(OpCodes.Ldloc, locals[i]);
                    if (locals[i].LocalType.IsValueType)
                    {
                        il.Emit(OpCodes.Box, locals[i].LocalType);
                    }
                    il.Emit(OpCodes.Stelem_Ref);
                }
            }

            il.Emit(OpCodes.Ret);
            FastInvokeHandler invoder = (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler));

            return(invoder);
        }
 public static void AddHashtable(MethodInfo key, FastInvokeHandler value)
 {
     s_methodsDIC.Add(key, value);
 }