Example #1
0
        public static MethodHandler CreateMethodHandler(MethodBase method)
        {
            var         dynam = new DynamicMethod(string.Empty, typeof(object), ManyObjects, Module, true);
            ILGenerator il    = dynam.GetILGenerator();

            ParameterInfo[] args = method.GetParameters();

            Label argsOK = il.DefineLabel();

            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldlen);
            il.Emit(OpCodes.Ldc_I4, args.Length);
            il.Emit(OpCodes.Beq, argsOK);

            il.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(Type.EmptyTypes));
            il.Emit(OpCodes.Throw);

            il.MarkLabel(argsOK);

            il.PushInstance(method.DeclaringType);

            for (int i = 0; i < args.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Ldc_I4, i);
                il.Emit(OpCodes.Ldelem_Ref);

                il.UnboxIfNeeded(args[i].ParameterType);
            }

            if (method.IsConstructor)
            {
                il.Emit(OpCodes.Newobj, method as ConstructorInfo);
            }
            else if (method.IsFinal || !method.IsVirtual)
            {
                il.Emit(OpCodes.Call, method as MethodInfo);
            }
            else
            {
                il.Emit(OpCodes.Callvirt, method as MethodInfo);
            }

            Type returnType = method.IsConstructor ? method.DeclaringType : (method as MethodInfo).ReturnType;

            if (returnType != typeof(void))
            {
                il.BoxIfNeeded(returnType);
            }
            else
            {
                il.Emit(OpCodes.Ldnull);
            }

            il.Emit(OpCodes.Ret);

            return((MethodHandler)dynam.CreateDelegate(typeof(MethodHandler)));
        }
Example #2
0
        public static Action <object, object> CreateFieldSetterHandler(FieldInfo fieldInfo)
        {
            var         dynam = new DynamicMethod(string.Empty, typeof(void), TwoObjects, Module, true);
            ILGenerator il    = dynam.GetILGenerator();

            if (!fieldInfo.IsStatic)
            {
                il.PushInstance(fieldInfo.DeclaringType);
            }

            il.Emit(OpCodes.Ldarg_1);
            il.UnboxIfNeeded(fieldInfo.FieldType);
            il.Emit(OpCodes.Stfld, fieldInfo);
            il.Emit(OpCodes.Ret);

            return((Action <object, object>)dynam.CreateDelegate(typeof(Action <object, object>)));
        }