Inheritance: System.Reflection.MethodInfo
Beispiel #1
1
        internal static GenericGetter CreateGetField(Type type, FieldInfo fieldInfo)
        {
            DynamicMethod dynamicGet = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type);

            ILGenerator il = dynamicGet.GetILGenerator();

            if (!type.IsClass) // structs
            {
                var lv = il.DeclareLocal(type);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Unbox_Any, type);
                il.Emit(OpCodes.Stloc_0);
                il.Emit(OpCodes.Ldloca_S, lv);
                il.Emit(OpCodes.Ldfld, fieldInfo);
                if (fieldInfo.FieldType.IsValueType)
                    il.Emit(OpCodes.Box, fieldInfo.FieldType);
            }
            else
            {
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, fieldInfo);
                if (fieldInfo.FieldType.IsValueType)
                    il.Emit(OpCodes.Box, fieldInfo.FieldType);
            }

            il.Emit(OpCodes.Ret);

            return (GenericGetter)dynamicGet.CreateDelegate(typeof(GenericGetter));
        }
Beispiel #2
0
        private static SetControlsDelegate GetSetControlsDelegate()
        {
            SetControlsDelegate handler                = null;
            FieldInfo           controls               = GetField("_controls");
            FieldInfo           occasionalFields       = GetField("_occasionalFields");
            MethodInfo          ensureOccasionalFields = GetMethod("EnsureOccasionalFields");

            SecurityCritical.ExecutePrivileged(new PermissionSet(PermissionState.Unrestricted), delegate
            {
                System.Reflection.Emit.DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("set_Controls ", null, new Type[] { typeof(Control), typeof(ControlCollection) }, typeof(Control).Module, true);
                ILGenerator il      = dm.GetILGenerator();
                Label occFieldsNull = il.DefineLabel();
                Label setControls   = il.DefineLabel();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, occasionalFields);
                il.Emit(OpCodes.Brfalse_S, occFieldsNull);
                il.MarkLabel(setControls);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Stfld, controls);
                il.Emit(OpCodes.Ret);
                il.MarkLabel(occFieldsNull);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Call, ensureOccasionalFields);
                il.Emit(OpCodes.Br, setControls);
                handler = (SetControlsDelegate)dm.CreateDelegate(typeof(SetControlsDelegate));
            });
            return(handler);
        }
Beispiel #3
0
 protected virtual Delegate CreateCastDelegate()
 {
     var paramTypes = _delegateParams.Select(x => x.ParameterType).ToArray();
     var m = new DynamicMethod(string.Empty, _delegateReturn, paramTypes,
         typeof (DelegateBuilder), SimpleReflection.PrivateAccess);
     var cg = m.GetILGenerator();
     // Prepare parameters...
     foreach (var parameterMap in _parametersMap)
     {
         parameterMap.EmitPrepare(cg);
     }
     // Load parameters, stack should be empty here
     foreach (var parameterMap in _parametersMap)
     {
         parameterMap.EmitLoad(cg);
     }
     // Emit invoke
     EmitInvoke(cg);
     // Emit finish, stack should contain return value here (if not void)
     foreach (var parameterMap in _parametersMap)
     {
         parameterMap.EmitFinish(cg);
     }
     // Emit return
     cg.Emit(OpCodes.Ret);
     return m.CreateDelegate(_delegateType);
 }
        /// <summary>
        /// Gets or creates an injector for the specified property.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <returns>The created injector.</returns>
        public PropertyInjector Create(PropertyInfo property)
        {
            #if NO_SKIP_VISIBILITY
            var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) });
            #else
            var dynamicMethod = new DynamicMethod(GetAnonymousMethodName(), typeof(void), new[] { typeof(object), typeof(object) }, true);
            #endif
            
            ILGenerator il = dynamicMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            EmitUnboxOrCast(il, property.DeclaringType);

            il.Emit(OpCodes.Ldarg_1);
            EmitUnboxOrCast(il, property.PropertyType);

            #if !SILVERLIGHT
            bool injectNonPublic = Settings.InjectNonPublic;
            #else
            const bool injectNonPublic = false;
            #endif // !SILVERLIGHT

            EmitMethodCall(il, property.GetSetMethod(injectNonPublic));
            il.Emit(OpCodes.Ret);

            return (PropertyInjector) dynamicMethod.CreateDelegate(typeof(PropertyInjector));
        }
Beispiel #5
0
        public static DynamicConstructor CreateConstructor(ConstructorInfo constructor)
        {
            if (constructor == null)
            {
                throw new ArgumentNullException("constructor");
            }
            if (constructor.GetParameters().Length > 0)
            {
                throw new NotSupportedException("Constructor with parameters are not supported.");
            }

            var dm = new System.Reflection.Emit.DynamicMethod(
                "ctor",
                MethodAttributes.Static | MethodAttributes.Public,
                CallingConventions.Standard,
                constructor.DeclaringType,
                Type.EmptyTypes,
                (Type)null,
                true);

            ILGenerator il = dm.GetILGenerator();

            il.Emit(OpCodes.Nop);
            il.Emit(OpCodes.Newobj, constructor);
            il.Emit(OpCodes.Ret);

            return((DynamicConstructor)dm.CreateDelegate(typeof(DynamicConstructor)));
        }
        public static Delegate Transcribe(Type sourceEventHandlerType, Delegate destinationEventHandler)
        {
            if (destinationEventHandler == null)
                throw new ArgumentNullException("destinationEventHandler");
            if (destinationEventHandler.GetType() == sourceEventHandlerType)
                return destinationEventHandler; // already OK

            var sourceArgs = VerifyStandardEventHandler(sourceEventHandlerType);
            var destinationArgs = VerifyStandardEventHandler(destinationEventHandler.GetType());
            var name = "_wrap" + Interlocked.Increment(ref methodIndex);
            var paramTypes = new Type[sourceArgs.Length + 1];

            paramTypes[0] = destinationEventHandler.GetType();
            for (int i = 0; i < sourceArgs.Length; i++)
            {
                paramTypes[i + 1] = sourceArgs[i].ParameterType;
            }

            var dynamicMethod = new DynamicMethod(name, null, paramTypes);
            var invoker = paramTypes[0].GetMethod("Invoke");
            var ilGenerator = dynamicMethod.GetILGenerator();
            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Ldarg_1);
            ilGenerator.Emit(OpCodes.Ldarg_2);

            if (!destinationArgs[1].ParameterType.IsAssignableFrom(sourceArgs[1].ParameterType))
            {
                ilGenerator.Emit(OpCodes.Castclass, destinationArgs[1].ParameterType);
            }
            ilGenerator.Emit(OpCodes.Call, invoker);
            ilGenerator.Emit(OpCodes.Ret);

            return dynamicMethod.CreateDelegate(sourceEventHandlerType, destinationEventHandler);
        }
        public static EmptyCtorDelegate GetConstructorMethodToCache(Type type)
        {
            ConstructorInfo emptyCtor = type.GetConstructor(Type.EmptyTypes);

            if (emptyCtor != null)
            {
#if MONOTOUCH || c || XBOX
                return(() => Activator.CreateInstance(type));
#elif WINDOWS_PHONE
                return(Expression.Lambda <EmptyCtorDelegate>(Expression.New(type)).Compile());
#else
#if SILVERLIGHT
                var dm = new System.Reflection.Emit.DynamicMethod("MyCtor", type, Type.EmptyTypes);
#else
                var dm = new DynamicMethod("MyCtor", type, Type.EmptyTypes, typeof(ServiceStackTextHelpers).Module, true);
#endif
                ILGenerator ilgen = dm.GetILGenerator();
                ilgen.Emit(OpCodes.Nop);
                ilgen.Emit(OpCodes.Newobj, emptyCtor);
                ilgen.Emit(OpCodes.Ret);

                return((EmptyCtorDelegate)dm.CreateDelegate(typeof(EmptyCtorDelegate)));
#endif
            }

#if (SILVERLIGHT && !WINDOWS_PHONE) || XBOX
            return(() => Activator.CreateInstance(type));
#elif WINDOWS_PHONE
            return(Expression.Lambda <EmptyCtorDelegate>(Expression.New(type)).Compile());
#else
            //Anonymous types don't have empty constructors
            return(() => FormatterServices.GetUninitializedObject(type));
#endif
        }
Beispiel #8
0
        private static CloneHandler CreateCloneWrapper(Type type)
        {
            var cloneMethod = new DynamicMethod
            (
                "NativeClone",
                MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.NewSlot,
                CallingConventions.Standard,
                typeof(IntPtr), new Type[] { type },
                type, false
            );
            var ilGenerator = cloneMethod.GetILGenerator();
            ilGenerator.Emit(OpCodes.Ldarg_0); // Step 1: Push the object to clone on the stack
            // Just to be clean, don't suppose ICloneable only has one member…
            var cloneableInterfaceMap = type.GetInterfaceMap(typeof(ICloneable));
            for (int i = 0; i < cloneableInterfaceMap.InterfaceMethods.Length; i++)
                if (cloneableInterfaceMap.InterfaceMethods[i].Name == "Clone")
                {
                    ilGenerator.Emit(OpCodes.Call, cloneableInterfaceMap.TargetMethods[i]); // Step 2: clone it
                    goto CloneMethodFound; // Finish the job once we found the Clone method (which should always be found)
                }
            throw new InvalidOperationException(); // This line should never be reached
            CloneMethodFound:
            ilGenerator.Emit(OpCodes.Isinst, type); // Step 3: Cast it to the correct type
            var nativePointerProperty = type.GetProperty
            (
                "NativePointer",
                BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder,
                typeof(IntPtr), Type.EmptyTypes, null
            );
            ilGenerator.Emit(OpCodes.Call, nativePointerProperty.GetGetMethod(true)); // Step 4: Get the native pointer
            ilGenerator.Emit(OpCodes.Ret); // Step 5: Return the value

            return cloneMethod.CreateDelegate(typeof(CloneHandler)) as CloneHandler;
        }
Beispiel #9
0
        /// <summary>Gets the instance creator delegate that can be use to create instances of the specified type.</summary>
        /// <param name="type">The type of the objects we want to create.</param>
        /// <returns>A delegate that can be used to create the objects.</returns>
        public static FastCreateInstanceHandler GetInstanceCreator(Type type)
        {
            lock (dictCreator)
            {
                if (dictCreator.ContainsKey(type)) return (FastCreateInstanceHandler)dictCreator[type];

                // generates a dynamic method to generate a FastCreateInstanceHandler delegate
                DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, type, new Type[0], typeof(DynamicCalls).Module);

                ILGenerator ilGenerator = dynamicMethod.GetILGenerator();

                // generates code to create a new object of the specified type using the default constructor
                ilGenerator.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));

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

                // converts the DynamicMethod to a FastCreateInstanceHandler delegate to create the object
                FastCreateInstanceHandler creator = (FastCreateInstanceHandler)dynamicMethod.CreateDelegate(typeof(FastCreateInstanceHandler));

                dictCreator.Add(type, creator);

                return creator;
            }
        }
Beispiel #10
0
        /// <summary>
        /// 指定したイベントに追加出来るようなイベントハンドラを作成し、<see cref="System.Delegate"/> として返します。
        /// イベントハンドラ内では、 this.OnChanged(sender) を呼び出します。
        /// </summary>
        /// <param name="e">追加先のイベントの情報を指定します。</param>
        /// <returns>作成したメソッドを参照するデリゲートを返します。</returns>
        protected System.Delegate CreateEventHandler(System.Reflection.EventInfo e)
        {
            System.Reflection.MethodInfo minfo = e.EventHandlerType.GetMethod("Invoke");
            if (minfo.ReturnType != typeof(void))
            {
                throw new System.ApplicationException(@"このイベントには返値を指定しなければ為りません。
現在、返値を必要とするイベントへのフックには対応していません。");
            }

            //-- 引数の型
            System.Reflection.ParameterInfo[] infoParams = minfo.GetParameters();
            System.Type[] tParams = new System.Type[infoParams.Length];
            tParams[0] = typeof(PropertyAccessor);           // this-parameter
            for (int i = 0; i < infoParams.Length; i++)
            {
                tParams[i + 1] = infoParams[i].ParameterType;
            }

            Emit.DynamicMethod eh = new Emit.DynamicMethod("eh", null, tParams, typeof(PropertyAccessor));

            System.Reflection.Emit.ILGenerator ilgen = eh.GetILGenerator();
            ilgen.Emit(Emit.OpCodes.Ldarg_0);                                                   // load this
            ilgen.Emit(infoParams.Length == 0?Emit.OpCodes.Ldnull:Emit.OpCodes.Ldarg_1);        // load sender (引数がない場合には null)
            ilgen.Emit(Emit.OpCodes.Callvirt, typeof(PropertyAccessor).GetMethod("OnChanged")); // this.OnChnaged(sender);
            ilgen.Emit(Emit.OpCodes.Ret);                                                       // return;

            return(eh.CreateDelegate(e.EventHandlerType, this));
        }
Beispiel #11
0
        public static DynamicMemberSetter CreateFieldSetter(FieldInfo field)
        {
            if (field == null)
            {
                throw new ArgumentNullException("field");
            }

            var dm = new System.Reflection.Emit.DynamicMethod("flds", null,
                                                              new[] { typeof(object), typeof(object) },
                                                              field.DeclaringType, true);

            ILGenerator il = dm.GetILGenerator();

            if (!field.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }
            il.Emit(OpCodes.Ldarg_1);

            EmitCastToReference(il, field.FieldType);

            if (!field.IsStatic)
            {
                il.Emit(OpCodes.Stfld, field);
            }
            else
            {
                il.Emit(OpCodes.Stsfld, field);
            }
            il.Emit(OpCodes.Ret);

            return((DynamicMemberSetter)dm.CreateDelegate(typeof(DynamicMemberSetter)));
        }
		internal override Delegate CreateDelegate () {
			DynamicMethod method = new DynamicMethod (Guid.NewGuid ().ToString (), typeof (IntPtr), ParameterTypes, module, true);
			ILGenerator il = method.GetILGenerator ();
			
			il.DeclareLocal (typeof (object));

			il.Emit (OpCodes.Ldtoken, cinfo.DeclaringType);
			il.Emit (OpCodes.Call, gettype);
			il.Emit (OpCodes.Call, newobject);
			il.Emit (OpCodes.Stloc_0);
			il.Emit (OpCodes.Ldloc_0);
			il.Emit (OpCodes.Ldarg_0);
			il.Emit (OpCodes.Stfld, handlefld);

			il.Emit (OpCodes.Ldloc_0);
			for (int i = 2; i < ParameterTypes.Length; i++) {
				il.Emit (OpCodes.Ldarg, i);
			}
			il.Emit (OpCodes.Call, cinfo);

			il.Emit (OpCodes.Ldarg_0);
			il.Emit (OpCodes.Ret);

			return method.CreateDelegate (DelegateType);
		}
 static Action<IDbCommand, bool> GetBindByName(Type commandType)
 {
     if (commandType == null) return null; // GIGO
     Action<IDbCommand, bool> action;
     if (Link<Type, Action<IDbCommand, bool>>.TryGet(bindByNameCache, commandType, out action))
     {
         return action;
     }
     var prop = commandType.GetProperty("BindByName", BindingFlags.Public | BindingFlags.Instance);
     action = null;
     ParameterInfo[] indexers;
     MethodInfo setter;
     if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool)
         && ((indexers = prop.GetIndexParameters()) == null || indexers.Length == 0)
         && (setter = prop.GetSetMethod()) != null
         )
     {
         var method = new DynamicMethod(commandType.Name + "_BindByName", null, new Type[] { typeof(IDbCommand), typeof(bool) });
         var il = method.GetILGenerator();
         il.Emit(OpCodes.Ldarg_0);
         il.Emit(OpCodes.Castclass, commandType);
         il.Emit(OpCodes.Ldarg_1);
         il.EmitCall(OpCodes.Callvirt, setter, null);
         il.Emit(OpCodes.Ret);
         action = (Action<IDbCommand, bool>)method.CreateDelegate(typeof(Action<IDbCommand, bool>));
     }
     // cache it            
     Link<Type, Action<IDbCommand, bool>>.TryAdd(ref bindByNameCache, commandType, ref action);
     return action;
 }
Beispiel #14
0
 private void Compile()
 {
     DynamicMethod isMatch = new DynamicMethod("IsMatch", typeof(bool), new Type[] { typeof(int), typeof(int) }, typeof(Schedule));
     ILGenerator il = isMatch.GetILGenerator();
     Label matched = il.DefineLabel();
     Label failed = il.DefineLabel();
     Console.WriteLine(mPositiveRules.Length);
     for (int i = 0; i < mPositiveRules.Length; i++)
     {
         ScheduleRuleSpan ruleSpan = mPositiveRules[i];
         for (int j = 0; j < ruleSpan.Rules.Length; j++)
         {
             ruleSpan.Rules[j].Compile(il);
             il.Emit(OpCodes.Brtrue, matched);
         }
     }
     il.Emit(OpCodes.Br, failed);
     il.MarkLabel(matched);
     il.Emit(OpCodes.Ldc_I4_1);
     il.Emit(OpCodes.Ret);
     il.MarkLabel(failed);
     il.Emit(OpCodes.Ldc_I4_0);
     il.Emit(OpCodes.Ret);
     mMatch = (IsDateMatch)isMatch.CreateDelegate(typeof(IsDateMatch));
 }
        public static GetValueDelegate CreateFieldGetter(FieldInfo field)
        {
            if (field == null)
                throw new ArgumentNullException("field");

            DynamicMethod dm = new DynamicMethod("FieldGetter", typeof(object),
                new Type[] { typeof(object) },
                field.DeclaringType, true);

            ILGenerator il = dm.GetILGenerator();

            if (!field.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);

                EmitCastToReference(il, field.DeclaringType);  //to handle struct object

                il.Emit(OpCodes.Ldfld, field);
            }
            else
                il.Emit(OpCodes.Ldsfld, field);

            if (field.FieldType.IsValueType)
                il.Emit(OpCodes.Box, field.FieldType);

            il.Emit(OpCodes.Ret);

            return (GetValueDelegate)dm.CreateDelegate(typeof(GetValueDelegate));
        }
        internal static void CreateMethodBody(Emit.DynamicMethod dynamicMethod, DynamicMethodRequest methodRequest, Type[] args)
        {
            var generator = dynamicMethod.GetILGenerator();

            for (var i = 0; i < args.Length; i++)
            {
                generator.Emit(OpCodes.Ldarg, i);
            }

            if (methodRequest.Member is MethodInfo)
            {
                var method = (MethodInfo)methodRequest.Member;
                var opCode = methodRequest.IsStatic ? OpCodes.Call : OpCodes.Callvirt;

                generator.EmitCall(opCode, method, null);
            }
            else if (methodRequest.Member is FieldInfo)
            {
                var method  = (FieldInfo)methodRequest.Member;
                var isInput = methodRequest.DataFlowDirection == DataFlowDirection.Input;
                var opCode  = methodRequest.IsStatic
                    ? (isInput ? OpCodes.Stsfld : OpCodes.Ldsfld)
                    : (isInput ? OpCodes.Stfld : OpCodes.Ldfld);

                generator.Emit(opCode, method);
            }

            generator.Emit(OpCodes.Ret);
        }
Beispiel #17
0
    private static void CtorProxy(RuntimeFieldHandle f)
    {
        var fld = FieldInfo.GetFieldFromHandle(f);
        var asm = Assembly.GetExecutingAssembly();

        char[] ch = new char[fld.Name.Length];
        for (int i = 0; i < ch.Length; i++)
        {
            ch[i] = (char)((byte)fld.Name[i] ^ i);
        }
        var mtd = asm.GetModules()[0].ResolveMethod(BitConverter.ToInt32(Convert.FromBase64String(new string(ch)), 0) ^ 0x12345678) as System.Reflection.ConstructorInfo;

        var args = mtd.GetParameters();

        Type[] arg = new Type[args.Length];
        for (int i = 0; i < args.Length; i++)
        {
            arg[i] = args[i].ParameterType;
        }

        var dm  = new System.Reflection.Emit.DynamicMethod("", mtd.DeclaringType, arg, mtd.DeclaringType, true);
        var gen = dm.GetILGenerator();

        for (int i = 0; i < arg.Length; i++)
        {
            gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_S, i);
        }
        gen.Emit(System.Reflection.Emit.OpCodes.Newobj, mtd);
        gen.Emit(System.Reflection.Emit.OpCodes.Ret);

        fld.SetValue(null, dm.CreateDelegate(fld.FieldType));
    }
        private static NetDynamicMethod CreateDynamicMethodInternal(string methodName, Type returnType, Type[] argumentTypes, MemberInfo member, bool skipVisibility)
        {
            NetDynamicMethod dm;

            dm = new NetDynamicMethod(methodName, returnType, argumentTypes, member.Module, skipVisibility);
            return(dm);
        }
Beispiel #19
0
 private void GenerateMethodBody(DynamicMethod method, Operation operation)
 {
     ILGenerator generator = method.GetILGenerator();
     generator.DeclareLocal(typeof(double));
     GenerateMethodBody(generator, operation);
     generator.Emit(OpCodes.Ret);
 }
Beispiel #20
0
		/// <summary>
		/// Generates a dynamic method which creates a new instance of <paramref name="type" />
		/// when invoked.
		/// </summary>
		private CreateInstanceInvoker CreateCreateInstanceMethod(System.Type type)
		{
			if (type.IsInterface || type.IsAbstract)
			{
				return null;
			}

			DynamicMethod method = new DynamicMethod(string.Empty, typeof(object), null, type, true);

			ILGenerator il = method.GetILGenerator();

			if (type.IsValueType)
			{
				LocalBuilder tmpLocal = il.DeclareLocal(type);
				il.Emit(OpCodes.Ldloca, tmpLocal);
				il.Emit(OpCodes.Initobj, type);
				il.Emit(OpCodes.Ldloc, tmpLocal);
				il.Emit(OpCodes.Box, type);
			}
			else
			{
				ConstructorInfo constructor = ReflectHelper.GetDefaultConstructor(type);
				if (constructor == null)
				{
					throw new InstantiationException("Object class " + type + " must declare a default (no-argument) constructor", type);
				}
				il.Emit(OpCodes.Newobj, constructor);
			}

			il.Emit(OpCodes.Ret);

			return (CreateInstanceInvoker)method.CreateDelegate(typeof(CreateInstanceInvoker));
		}
Beispiel #21
0
		private static DynamicGetter CreateGetMethod(PropertyInfo propertyInfo, Type type)
		{
			var getMethod = propertyInfo.GetGetMethod();

			if (getMethod == null)
				throw new InvalidOperationException(string.Format("Could not retrieve GetMethod for the {0} property of {1} type", propertyInfo.Name, type.FullName));

			var arguments = new Type[1]
			{
				typeof (object)
			};

			var getterMethod = new DynamicMethod(string.Concat("_Get", propertyInfo.Name, "_"), typeof(object), arguments, propertyInfo.DeclaringType);
			var generator = getterMethod.GetILGenerator();

			generator.DeclareLocal(typeof(object));
			generator.Emit(OpCodes.Ldarg_0);
			generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
			generator.EmitCall(OpCodes.Callvirt, getMethod, null);

			if (propertyInfo.PropertyType.IsClass == false)
				generator.Emit(OpCodes.Box, propertyInfo.PropertyType);

			generator.Emit(OpCodes.Ret);

			return (DynamicGetter) getterMethod.CreateDelegate(typeof (DynamicGetter));
		}
        internal static Func<object, SqlArgument[]> CreateGetInsertValues(IObjectInfo objectInfo)
        {
            var dynamicMethod = new DynamicMethod(
                name: "MicroLite" + objectInfo.ForType.Name + "GetInsertValues",
                returnType: typeof(SqlArgument[]),
                parameterTypes: new[] { typeof(object) }, // arg_0
                m: typeof(ObjectInfo).Module);

            var ilGenerator = dynamicMethod.GetILGenerator();

            ilGenerator.DeclareLocal(objectInfo.ForType);     // loc_0 - {Type} instance;
            ilGenerator.DeclareLocal(typeof(SqlArgument[]));  // loc_1 - SqlArgument[] sqlArguments;

            // instance = ({Type})arg_0;
            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Castclass, objectInfo.ForType);
            ilGenerator.Emit(OpCodes.Stloc_0);

            // sqlArguments = new SqlArgument[count];
            ilGenerator.EmitEfficientInt(objectInfo.TableInfo.InsertColumnCount);
            ilGenerator.Emit(OpCodes.Newarr, typeof(SqlArgument));
            ilGenerator.Emit(OpCodes.Stloc_1);

            EmitGetPropertyValues(ilGenerator, objectInfo, c => c.AllowInsert);

            // return sqlArguments;
            ilGenerator.Emit(OpCodes.Ldloc_1);
            ilGenerator.Emit(OpCodes.Ret);

            var getInsertValues = (Func<object, SqlArgument[]>)dynamicMethod.CreateDelegate(typeof(Func<object, SqlArgument[]>));

            return getInsertValues;
        }
        public Activator CreateActivator(Type type, out List<Type> dependencies)
        {
            dependencies = new List<Type>();

            ConstructorInfo constructorInfo = type.GetConstructors()[0];

            ParameterInfo[] parameters = constructorInfo.GetParameters();

            var method = new DynamicMethod("CreateInstance", typeof(object), new[] { typeof(object[]) });

            ILGenerator generator = method.GetILGenerator();

            for (int index = 0; index < parameters.Length; index++)
            {
                Type parameterType = parameters[index].ParameterType;

                dependencies.Add(parameterType);

                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldc_I4, index);
                generator.Emit(OpCodes.Ldelem_Ref);
                generator.Emit(parameterType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, parameterType);
            }

            generator.Emit(OpCodes.Newobj, constructorInfo);
            generator.Emit(OpCodes.Ret);

            var activator = method.CreateDelegate(typeof(Activator)) as Activator;

            return activator;
        }
Beispiel #24
0
        public BehaviorModel()
        {
            var modelType = GetType();
            if (!s_data.TryGetValue(modelType, out m_data))
            {
                lock (s_data)
                {
                    if (!s_data.TryGetValue(modelType, out m_data))
                    {
                        m_data = new BehaviorModelData
                        {
                            BhvModelAttr = modelType.GetAttribute<BehaviorModelAttribute>()
                        };
                        var bhvType = m_data.BhvModelAttr != null
                                      ? m_data.BhvModelAttr.BehaviorType
                                      : SupplementBehaviorType; // virtual function call to get the most derived value

                        var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + bhvType.FullName, bhvType, null, bhvType);
                        var ilGen = dynMethod.GetILGenerator();
                        ilGen.Emit(OpCodes.Newobj, bhvType.GetConstructor(Type.EmptyTypes));
                        ilGen.Emit(OpCodes.Ret);

                        m_data.BehaviorType = bhvType;
                        m_data.BhvFactory = (Func<IBehavior>)dynMethod.CreateDelegate(typeof(Func<IBehavior>));
                        m_data.IsBehaviorStatic = BehaviorModel.GetIsBehaviorStatic(bhvType);
                        s_data.Add(modelType, m_data);
                    }
                }
            }

            m_name = null;
        }
        private static object GetDynamicInstance(Type type) {
            if (typeof (MulticastDelegate).IsAssignableFrom(type)) {
                DynamicMethod method = new DynamicMethod("XStreamDynamicDelegate", typeof (void), GetDelegateParameterTypes(type), typeof (object));
                ILGenerator generator = method.GetILGenerator();
                generator.Emit(OpCodes.Ret);
                return method.CreateDelegate(type);
            }
            if (type.IsSealed)
                throw new ConversionException("Impossible to construct type: " + type);

            // Check if we already have the type defined
            string typeName = prefix + type;
            lock (typeMap) {
                Type dynamicType = typeMap[typeName] as Type;

                if (dynamicType == null) {
                    TypeBuilder typeBuilder = ModuleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.NotPublic, type);

                    ConstructorBuilder cb = typeBuilder.DefineConstructor(MethodAttributes.Private, CallingConventions.Standard, new Type[0]);
                    cb.GetILGenerator().Emit(OpCodes.Ret);

                    dynamicType = typeBuilder.CreateType();
                    typeMap[typeName] = dynamicType;
                }

                return Activator.CreateInstance(dynamicType, true);
            }
        }
Beispiel #26
0
        public RedisFactory(bool saveDynamicAssembly = false)
        {
            var redisTypes = RedisTypeBuilder.BuildRedisTypes();

            if (saveDynamicAssembly)
            {
                redisTypes.SaveAssembly();
            }

            // Build CreateRedis dynamic method

            var createRedisDynamicMethod = new DynamicMethod("CreateRedis", typeof(IRedis), new[] { typeof(IRedisConnection) });
            var redisConstructor = redisTypes.RedisType.GetConstructor(new[] { typeof(IRedisConnection) });

            var createRedisGenerator = createRedisDynamicMethod.GetILGenerator();
            createRedisGenerator.Emit(OpCodes.Ldarg_0);
            createRedisGenerator.Emit(OpCodes.Newobj, redisConstructor);
            createRedisGenerator.Emit(OpCodes.Ret);

            // Build CreateRedisExec dynamic method

            var createRedisPipelineDynamicMethod = new DynamicMethod("CreateRedisPipeline", typeof(IRedisPipeline), new[] { typeof(IRedisConnection), typeof(bool) });
            var redisPipelineConstructor = redisTypes.RedisPipelineType.GetConstructor(new[] { typeof(IRedisConnection), typeof(bool) });

            var createRedisPipelineGenerator = createRedisPipelineDynamicMethod.GetILGenerator();
            createRedisPipelineGenerator.Emit(OpCodes.Ldarg_0);
            createRedisPipelineGenerator.Emit(OpCodes.Ldarg_1);
            createRedisPipelineGenerator.Emit(OpCodes.Newobj, redisPipelineConstructor);
            createRedisPipelineGenerator.Emit(OpCodes.Ret);

            // Create delegates from dynamic methods

            this.createRedis = (CreateRedisDelegate) createRedisDynamicMethod.CreateDelegate(typeof (CreateRedisDelegate));
            this.createRedisPipeline = (CreateRedisPipelineDelegate)createRedisPipelineDynamicMethod.CreateDelegate(typeof(CreateRedisPipelineDelegate));
        }
        internal static Delegate CreateEmptyDelegate(this Type delegateType)
        {
            if (delegateType == null) {
                throw new ArgumentNullException("delegateType");
            }
            if (delegateType.BaseType != typeof (MulticastDelegate)) {
                throw new ArgumentException("must be a delegate", "delegateType");
            }

            return _emptyDelegates.GetOrAdd(delegateType, () => {
                var delegateReturnType = delegateType.GetDelegateReturnType();

                var dynamicMethod = new DynamicMethod(string.Empty, delegateReturnType, delegateType.GetDelegateParameterTypes().ToArray());
                var il = dynamicMethod.GetILGenerator();

                if (delegateReturnType.FullName != "System.Void") {
                    if (delegateReturnType.IsValueType) {
                        il.Emit(OpCodes.Ldc_I4, 0);
                    } else {
                        il.Emit(OpCodes.Ldnull);
                    }
                }
                il.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(delegateType);
            });
        }
Beispiel #28
0
        private static CreateInstanceInvoker CreateCreateInstanceMethod(Type type)
        {
            if (type.IsInterface || type.IsAbstract)
                return null;

            DynamicMethod method = new DynamicMethod(string.Empty, typeof (object), null, type, true);

            ILGenerator il = method.GetILGenerator();

            if (type.IsValueType)
            {
                LocalBuilder tmpLocal = il.DeclareLocal(type);
                il.Emit(OpCodes.Ldloca, tmpLocal);
                il.Emit(OpCodes.Initobj, type);
                il.Emit(OpCodes.Ldloc, tmpLocal);
                il.Emit(OpCodes.Box, type);
            }
            else
            {
                ConstructorInfo constructor = type.GetConstructor(AnyVisibilityInstance, null, CallingConventions.HasThis, NoClasses, null);
                if (constructor == null)
                    throw new ApplicationException("Object class " + type + " must declare a default (no-argument) constructor");

                il.Emit(OpCodes.Newobj, constructor);
            }

            il.Emit(OpCodes.Ret);

            return (CreateInstanceInvoker) method.CreateDelegate(typeof (CreateInstanceInvoker));
        }
 public DynamicMethodHelper(string name, Type returnType, Type[] parameterTypes)
 {
     this.method = new DynamicMethod(name, returnType, parameterTypes,
         this.GetType(),
         true
         );
 }
Beispiel #30
0
		public void TestCall2()
		{
			var parameters = new[] { typeof(int), typeof(int) };

			var dm = new DynamicMethod("soma", typeof(int), parameters);

			var gen = dm.GetILGenerator();

			gen.DeclareLocal (typeof(Math));
			var ctor = typeof(Math).GetConstructors () [0];

			gen.Emit (OpCodes.Newobj, ctor);
			gen.Emit (OpCodes.Stloc, 0);
            gen.Emit (OpCodes.Ldobj, 0);

			//gen.Emit(OpCodes.Ldarg_0);
			//gen.Emit(OpCodes.Ldarg_1);
			//var soma = GetType ().GetMethod ("Soma");

			//gen.EmitCall (OpCodes.Callvirt, soma, new Type[] {  });

			gen.Emit (OpCodes.Ldc_I4, 2);

			gen.Emit(OpCodes.Ret);

			var result = dm.Invoke(null, new object[] { 1, 1 });

			//var func = (Func<int, int, int>)dm.CreateDelegate(typeof(Func<int, int, int>));

			Assert.AreEqual (2, result);
		}          
Beispiel #31
0
		private void GenerateMethodBody(DynamicMethod dynamicMethod) {
			var ilGenerator = dynamicMethod.GetILGenerator();
			ilGenerator.Emit(OpCodes.Ldarg_0); // Load templateControl argument onto stack
			ilGenerator.Emit(OpCodes.Ldarg_1); // Load virtualPath argument onto stack
			ilGenerator.Emit(OpCodes.Call, invoker); // Invoke LoadControlInvoker with the loaded two arguments
			ilGenerator.Emit(OpCodes.Ret); // End method
		}
        //todo: temporary public
        public FillingDelegate GetFiller(TypeMappingInfo mapping, Table table)
        {
            var ct = typeof(object);
            // Fill(reader, obj, offset)
            Type[] methodArgs2 = { typeof(IDataRecord), ct, typeof(int) };
            var method = new DynamicMethod(
                "ct",
                null,
                methodArgs2, typeof(SqlValueMapper));

            var generator = method.GetILGenerator();

            Type type = mapping.Type;

            var i = 0;
            foreach(var prop in table.Columns)
            {
                var navigation = prop as NavigationPropertyMapping;
                if (navigation != null)
                {
                    GenerateForNavigationProperty(navigation, type, generator, i);
                }
                else
                {
                    GenerateForPrimitive(type, prop, generator, i);
                }
                i++;
            }
            // return
            generator.Emit(OpCodes.Ret);
            return (FillingDelegate)method.CreateDelegate(typeof(FillingDelegate));
        }
        public static SetValueDelegate CreateFieldSetter(FieldInfo field)
        {
            if (field == null)
                throw new ArgumentNullException("field");

            DynamicMethod dm = new DynamicMethod("FieldSetter", null,
                new Type[] { typeof(object), typeof(object) },
                field.DeclaringType, true);

            ILGenerator il = dm.GetILGenerator();

            if (!field.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }
            il.Emit(OpCodes.Ldarg_1);

            EmitCastToReference(il, field.FieldType);

            if (!field.IsStatic)
                il.Emit(OpCodes.Stfld, field);
            else
                il.Emit(OpCodes.Stsfld, field);
            il.Emit(OpCodes.Ret);

            return (SetValueDelegate)dm.CreateDelegate(typeof(SetValueDelegate));
        }
Beispiel #34
0
		static ResXProjectFile() {
			// Mono doesn't support the constructors that we need

			Type[] paramTypes;
			ConstructorInfo ctorInfo;

			paramTypes = new Type[] { typeof(string), typeof(Func<Type, string>) };
			ctorInfo = typeof(ResXResourceWriter).GetConstructor(paramTypes);
			if (ctorInfo != null) {
				var dynMethod = new DynamicMethod("ResXResourceWriter-ctor", typeof(ResXResourceWriter), paramTypes);
				var ilg = dynMethod.GetILGenerator();
				ilg.Emit(OpCodes.Ldarg_0);
				ilg.Emit(OpCodes.Ldarg_1);
				ilg.Emit(OpCodes.Newobj, ctorInfo);
				ilg.Emit(OpCodes.Ret);
				delegateResXResourceWriterConstructor = (Func<string, Func<Type, string>, ResXResourceWriter>)dynMethod.CreateDelegate(typeof(Func<string, Func<Type, string>, ResXResourceWriter>));
			}

			paramTypes = new Type[] { typeof(string), typeof(object), typeof(Func<Type, string>) };
			ctorInfo = typeof(ResXDataNode).GetConstructor(paramTypes);
			if (ctorInfo != null) {
				var dynMethod = new DynamicMethod("ResXDataNode-ctor", typeof(ResXDataNode), paramTypes);
				var ilg = dynMethod.GetILGenerator();
				ilg.Emit(OpCodes.Ldarg_0);
				ilg.Emit(OpCodes.Ldarg_1);
				ilg.Emit(OpCodes.Ldarg_2);
				ilg.Emit(OpCodes.Newobj, ctorInfo);
				ilg.Emit(OpCodes.Ret);
				delegateResXDataNodeConstructor = (Func<string, object, Func<Type, string>, ResXDataNode>)dynMethod.CreateDelegate(typeof(Func<string, object, Func<Type, string>, ResXDataNode>));
			}
		}
Beispiel #35
0
        private static PropertyMapper GenerateDelegate(Type sourceType, Type targetType, bool ignoreMappings)
        {
            var method = new DynamicMethod("Map_" + sourceType.FullName + "_" + targetType.FullName, null, new[] { typeof(object), typeof(object) });
            var il = method.GetILGenerator();

            var sourceProperties = Reflector.GetAllProperties(sourceType);
            var targetProperties = Reflector.GetAllProperties(targetType);

            var entityMap = MappingFactory.GetEntityMap(targetType);

            var matches = sourceProperties.CrossJoin(targetProperties).Where(t => t.Item2.Name == MappingFactory.GetPropertyOrColumnName(t.Item3, ignoreMappings, entityMap, false)
                                                                                    && t.Item2.PropertyType == t.Item3.PropertyType
                                                                                    && t.Item2.PropertyType.IsPublic
                                                                                    && t.Item3.PropertyType.IsPublic
                                                                                    //&& (t.Item3.PropertyType.IsValueType || t.Item3.PropertyType == typeof(string))
                                                                                    && t.Item2.CanRead && t.Item3.CanWrite);

            foreach (var match in matches)
            {
                il.Emit(OpCodes.Ldarg_1);
                il.EmitCastToReference(targetType);
                il.Emit(OpCodes.Ldarg_0);
                il.EmitCastToReference(sourceType);
                il.Emit(OpCodes.Callvirt, match.Item2.GetGetMethod());
                il.Emit(OpCodes.Callvirt, match.Item3.GetSetMethod());
            }
            il.Emit(OpCodes.Ret);

            var mapper = (PropertyMapper)method.CreateDelegate(typeof(PropertyMapper));
            return mapper;
        }
Beispiel #36
0
        /// <summary>
        /// the address of a field relative to the address an object reference of that type points to.  this function is very expensive to call.
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public static IntPtr GetManagedOffset(this FieldInfo field)
        {
            Type type = field.DeclaringType;

            var dyn = new System.Reflection.Emit.DynamicMethod(
                "xxz0", typeof(IntPtr), new Type[] { typeof(object) }, typeof(ReflectionExtensions).Module, true);
            var il = dyn.GetILGenerator();

            var pin      = il.DeclareLocal(type, true);
            var baseaddr = il.DeclareLocal(typeof(IntPtr));

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Stloc, pin);         // force cast object to type (invalid), and pin

            il.Emit(OpCodes.Ldloc, pin);         // base address of reference (points to typeinfo)
            il.Emit(OpCodes.Conv_I);             // convert object ref to intptr (invalid)
            il.Emit(OpCodes.Stloc, baseaddr);

            il.Emit(OpCodes.Ldloc, pin);
            il.Emit(OpCodes.Ldflda, field);      // address of desired field
            il.Emit(OpCodes.Conv_I);             // convert field& to intptr (invalid)
            il.Emit(OpCodes.Ldloc, baseaddr);
            il.Emit(OpCodes.Sub);
            il.Emit(OpCodes.Ret);

            return((IntPtr)dyn.Invoke(null, new object[] { new object() }));
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:DelegateFieldSetAccessor"/> class
        /// for field get access via DynamicMethod.
        /// </summary>
        /// <param name="targetObjectType">Type of the target object.</param>
        /// <param name="fieldName">Name of the field.</param>
        public DelegateFieldSetAccessor(Type targetObjectType, string fieldName)
        {
            // this.targetType = targetObjectType;
            _fieldName = fieldName;

            FieldInfo fieldInfo = targetObjectType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            // Make sure the field exists
            if (fieldInfo == null)
            {
                throw new NotSupportedException(
                    string.Format("Field \"{0}\" does not exist for type "
                    + "{1}.", fieldName, targetObjectType));
            }
            else
            {
                _fieldType = fieldInfo.FieldType;
                this.nullInternal = this.GetNullInternal(_fieldType);

                // Emit the IL for set access.
                DynamicMethod dynamicMethodSet = new DynamicMethod("SetImplementation", null, new Type[] { typeof(object), typeof(object) }, this.GetType().Module, false);
                ILGenerator ilgen = dynamicMethodSet.GetILGenerator();

                ilgen = dynamicMethodSet.GetILGenerator();

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

                _set = (SetValue)dynamicMethodSet.CreateDelegate(typeof(SetValue));
            }
        }
        internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size)
            : base(method, size)
        {
            m_scope = new DynamicScope();

            m_methodSigToken = m_scope.GetTokenFor(methodSignature);
        }
        internal static Func<object, object> CreateGetIdentifier(IObjectInfo objectInfo)
        {
            var dynamicMethod = new DynamicMethod(
                name: "MicroLite" + objectInfo.ForType.Name + "GetIdentifier",
                returnType: typeof(object),
                parameterTypes: new[] { typeof(object) }); // arg_0

            var ilGenerator = dynamicMethod.GetILGenerator();

            // var instance = ({Type})arg_0;
            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Castclass, objectInfo.ForType);

            // var identifier = instance.Id;
            ilGenerator.Emit(OpCodes.Callvirt, objectInfo.TableInfo.IdentifierColumn.PropertyInfo.GetGetMethod());

            // value = (object)identifier;
            ilGenerator.EmitBoxIfValueType(objectInfo.TableInfo.IdentifierColumn.PropertyInfo.PropertyType);

            // return identifier;
            ilGenerator.Emit(OpCodes.Ret);

            var getIdentifierValue = (Func<object, object>)dynamicMethod.CreateDelegate(typeof(Func<object, object>));

            return getIdentifierValue;
        }
Beispiel #40
0
        internal Execute GetDelegateIL(MethodInfo methodInfo)
        {
            //http://www.cnblogs.com/daizhj/archive/2008/06/20/1224818.html
            //http://www.cnblogs.com/xuanhun/archive/2012/06/22/2558698.html
            // 生成 方法

            /*
             * public T invoke( Class2 cls, object[] par)
             * {
             * return cls.mothd(par[0], par[1]);
             * }
             * IL_0000: nop
             * IL_0001: ldarg.1
             * IL_0002: ldarg.2
             * IL_0003: ldc.i4.0
             * IL_0004: ldelem.ref
             * IL_0005: ldarg.2
             * IL_0006: ldc.i4.1
             * IL_0007: ldelem.ref
             * IL_0008: callvirt instance object HY.Frame.Bis.Class2::mothd(string,  string)
             * IL_000d: stloc.0
             * IL_000e: br.s IL_0010
             *
             * IL_0010: ldloc.0
             * IL_0011: ret
             */
            //Type[] methodArgs = methodInfo.GetParameters().Select(a => a.ParameterType).ToArray();


            Type[] methodArgs = { typeof(object), typeof(object[]) };
            System.Reflection.Emit.DynamicMethod invoke = new System.Reflection.Emit.DynamicMethod("Invoke", typeof(object), methodArgs);
            ILGenerator il = invoke.GetILGenerator();

            il.Emit(OpCodes.Nop);
            il.Emit(OpCodes.Ldarg_1);
            for (int i = 0; i < methodArgs.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_2);
                il.Emit(OpCodes.Ldc_I4, i);
                il.Emit(OpCodes.Ldelem_Ref);
            }
            il.Emit(OpCodes.Callvirt, methodInfo);
            il.Emit(OpCodes.Ret);

            var exec = (Execute)invoke.CreateDelegate(typeof(Execute));

            /*
             * var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(, AssemblyBuilderAccess.RunAndSave);
             * var moduleBuilder = assemblyBuilder.DefineDynamicModule("MvcAdviceProviderModule", "test.dll", true);
             * TypeBuilder typeBuilder = moduleBuilder.DefineType("MvcAdviceProvider.MvcAdviceProviderType",
             * TypeAttributes.Public, typeof(object), new Type[] { typeof(IAssessmentAopAdviceProvider) });
             * assemblyBuilder.Save("runass");
             */
            return(exec);
        }
        /// <summary>
        /// Create a new method delegate for the specified method using <see cref="System.Reflection.Emit.DynamicMethod"/>
        /// </summary>
        /// <param name="methodInfo">the method to create the delegate for</param>
        /// <returns>a delegate that can be used to invoke the method.</returns>
        public static MethodDelegate CreateMethod(MethodInfo methodInfo)
        {
            Guard.ArgumentNotNull(methodInfo, "You cannot create a delegate for a null value.");

            bool             skipVisibility = true; // !IsPublic(methodInfo);
            NetDynamicMethod dm             = CreateDynamicMethod(methodInfo.Name, typeof(object), new Type[] { typeof(object), typeof(object[]) }, methodInfo, skipVisibility);
            ILGenerator      il             = dm.GetILGenerator();

            EmitInvokeMethod(il, methodInfo, false);
            return((MethodDelegate)dm.CreateDelegate(typeof(MethodDelegate)));
        }
Beispiel #42
0
        internal MethodBuilder(MethodName name)
        {
            Name = name;


            var invokeInfo     = typeof(Invokable).GetMethod("Invoke");
            var parameterTypes = (from param in invokeInfo.GetParameters() select param.ParameterType).ToArray();

            _dynamicMethod = new DynamicMethod(name.Simple, invokeInfo.ReturnType, parameterTypes, this.GetType());
            _g             = _dynamicMethod.GetILGenerator();
        }
        public static System.Reflection.Emit.DynamicMethod Eval(Node n)
        {
            var type  = GetTypeFromNode(n["DotName"]);
            var name  = n["Name"].Text;
            var types = n["ArgList"].GetNodes("Arg").Select(arg => GetTypeFromNode(arg["TypeName"])).ToArray();
            var r     = new System.Reflection.Emit.DynamicMethod(name, type, types, true);
            var e     = new ILCompiler(r.GetILGenerator());

            e.EmitTerm(n["Block"]);
            return(r);
        }
Beispiel #44
0
        /// <summary>
        /// Create a new Set method delegate for the specified field using <see cref="System.Reflection.Emit.DynamicMethod"/>
        /// </summary>
        /// <param name="fieldInfo">the field to create the delegate for</param>
        /// <returns>a delegate that can be used to read the field.</returns>
        /// <remarks>
        /// If the field's <see cref="FieldInfo.IsLiteral"/> returns true, the returned method
        /// will throw an <see cref="InvalidOperationException"/> when called.
        /// </remarks>
        public static FieldSetterDelegate CreateFieldSetter(FieldInfo fieldInfo)
        {
            AssertUtils.ArgumentNotNull(fieldInfo, "You cannot create a delegate for a null value.");

            bool skipVisibility = true; // !IsPublic(fieldInfo);

            System.Reflection.Emit.DynamicMethod dmSetter = CreateDynamicMethod("set_" + fieldInfo.Name, null, new Type[] { typeof(object), typeof(object) }, fieldInfo, skipVisibility);
            ILGenerator il = dmSetter.GetILGenerator();

            EmitFieldSetter(il, fieldInfo, false);
            return((FieldSetterDelegate)dmSetter.CreateDelegate(typeof(FieldSetterDelegate)));
        }
        /// <summary>
        /// Create a new Get method delegate for the specified property using <see cref="System.Reflection.Emit.DynamicMethod"/>
        /// </summary>
        /// <param name="propertyInfo">the property to create the delegate for</param>
        /// <returns>a delegate that can be used to read the property.</returns>
        /// <remarks>
        /// If the property's <see cref="PropertyInfo.CanRead"/> returns false, the returned method
        /// will throw an <see cref="InvalidOperationException"/> when called.
        /// </remarks>
        public static PropertyGetterDelegate CreatePropertyGetter(PropertyInfo propertyInfo)
        {
            Guard.ArgumentNotNull(propertyInfo, "You cannot create a delegate for a null value.");

            MethodInfo       getMethod      = propertyInfo.GetGetMethod();
            bool             skipVisibility = true; // (null == getMethod || !IsPublic(getMethod)); // getter is public
            NetDynamicMethod dm             = CreateDynamicMethod("get_" + propertyInfo.Name, typeof(object), new Type[] { typeof(object), typeof(object[]) }, propertyInfo, skipVisibility);
            ILGenerator      il             = dm.GetILGenerator();

            EmitPropertyGetter(il, propertyInfo, false);
            return((PropertyGetterDelegate)dm.CreateDelegate(typeof(PropertyGetterDelegate)));
        }
Beispiel #46
0
    private static void MtdProxy(RuntimeFieldHandle f)
    {
        var fld = System.Reflection.FieldInfo.GetFieldFromHandle(f);
        var asm = System.Reflection.Assembly.GetExecutingAssembly();

        char[] ch = new char[fld.Name.Length];
        for (int i = 0; i < ch.Length; i++)
        {
            ch[i] = (char)((byte)fld.Name[i] ^ i);
        }
        byte[] dat = Convert.FromBase64String(new string(ch));
        var    mtd = asm.GetModules()[0].ResolveMethod(BitConverter.ToInt32(dat, 1) ^ 0x12345678) as System.Reflection.MethodInfo;

        if (mtd.IsStatic)
        {
            fld.SetValue(null, Delegate.CreateDelegate(fld.FieldType, mtd));
        }
        else
        {
            var    tmp = mtd.GetParameters();
            Type[] arg = new Type[tmp.Length + 1];
            arg[0] = typeof(object);
            for (int i = 0; i < tmp.Length; i++)
            {
                arg[i + 1] = tmp[i].ParameterType;
            }

            System.Reflection.Emit.DynamicMethod dm;
            if (mtd.DeclaringType.IsInterface)
            {
                dm = new System.Reflection.Emit.DynamicMethod("", mtd.ReturnType, arg, (Type)null, true);
            }
            else
            {
                dm = new System.Reflection.Emit.DynamicMethod("", mtd.ReturnType, arg, mtd.DeclaringType, true);
            }
            var gen = dm.GetILGenerator();
            for (int i = 0; i < arg.Length; i++)
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Ldarg, i);
                if (i == 0)
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Castclass, mtd.DeclaringType);
                }
            }
            gen.Emit((dat[0] == '\r') ? System.Reflection.Emit.OpCodes.Callvirt : System.Reflection.Emit.OpCodes.Call, mtd);
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

            fld.SetValue(null, dm.CreateDelegate(fld.FieldType));
        }
    }
        internal (Delegate invoker, Type[] argTypes, Type declaringType) GetDelegate(DynamicMethodRequest methodRequest)
        {
            var declaringType = methodRequest.Member.DeclaringType;

            var argTypes = GetArgTypes(methodRequest);
            var method   = new Emit.DynamicMethod(methodRequest.Member.Name, methodRequest.ReturnType, argTypes);

            CreateMethodBody(method, methodRequest, argTypes);

            var delegateType = CreateDelegateType(argTypes, methodRequest.ReturnType);
            var invoker      = method.CreateDelegate(delegateType);

            return(invoker, argTypes, declaringType);
        }
Beispiel #48
0
        /// <summary>
        /// Create a new Set method delegate for the specified property using <see cref="System.Reflection.Emit.DynamicMethod"/>
        /// </summary>
        /// <param name="propertyInfo">the property to create the delegate for</param>
        /// <returns>a delegate that can be used to write the property.</returns>
        /// <remarks>
        /// If the property's <see cref="PropertyInfo.CanWrite"/> returns false, the returned method
        /// will throw an <see cref="InvalidOperationException"/> when called.
        /// </remarks>
        public static PropertySetterDelegate CreatePropertySetter(PropertyInfo propertyInfo)
        {
            AssertUtils.ArgumentNotNull(propertyInfo, "You cannot create a delegate for a null value.");

            MethodInfo setMethod      = propertyInfo.GetSetMethod();
            bool       skipVisibility = true; // (null == setMethod || !IsPublic(setMethod)); // setter is public

            Type[]           argumentTypes = new Type[] { typeof(object), typeof(object), typeof(object[]) };
            NetDynamicMethod dm            = CreateDynamicMethod("set_" + propertyInfo.Name, null, argumentTypes, propertyInfo, skipVisibility);
            ILGenerator      il            = dm.GetILGenerator();

            EmitPropertySetter(il, propertyInfo, false);
            return((PropertySetterDelegate)dm.CreateDelegate(typeof(PropertySetterDelegate)));
        }
Beispiel #49
0
        private static GetControlsDelegate GetGetControlsDelegate()
        {
            GetControlsDelegate handler  = null;
            FieldInfo           controls = GetField("_controls");

            SecurityCritical.ExecutePrivileged(new PermissionSet(PermissionState.Unrestricted), delegate
            {
                System.Reflection.Emit.DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("get_Controls", typeof(ControlCollection), new Type[] { typeof(Control) }, typeof(Control).Module, true);
                ILGenerator il = dm.GetILGenerator();
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldfld, controls);
                il.Emit(OpCodes.Ret);
                handler = (GetControlsDelegate)dm.CreateDelegate(typeof(GetControlsDelegate));
            });
            return(handler);
        }
        private static NetDynamicMethod CreateDynamicMethod(string methodName, Type returnType, Type[] argumentTypes, MemberInfo member, bool skipVisibility)
        {
            NetDynamicMethod dmGetter = null;

            methodName = "_dynamic_" + member.DeclaringType.FullName + "." + methodName;
            try
            {
                new PermissionSet(PermissionState.Unrestricted).Demand();
                dmGetter = CreateDynamicMethodInternal(methodName, returnType, argumentTypes, member, skipVisibility);
            }
            catch (SecurityException)
            {
                dmGetter = CreateDynamicMethodInternal(methodName, returnType, argumentTypes, MethodBase.GetCurrentMethod(), false);
            }
            return(dmGetter);
        }
        private static GetControlsDelegate GetGetControlsDelegate()
        {
            GetControlsDelegate handler = null;

            if (SystemUtils.Clr4Runtime)
            {
                FieldInfo controls = GetField("_controls");

                SecurityCritical.ExecutePrivileged(new PermissionSet(PermissionState.Unrestricted), delegate
                {
                    System.Reflection.Emit.DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("get_Controls", typeof(ControlCollection), new Type[] { typeof(Control) }, typeof(Control).Module, true);
                    ILGenerator il = dm.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldfld, controls);
                    il.Emit(OpCodes.Ret);
                    handler = (GetControlsDelegate)dm.CreateDelegate(typeof(GetControlsDelegate));
                });
            }
            else
            {
                FieldInfo occasionalFields = GetField("_occasionalFields");
                MethodInfo ensureOccasionalFields = GetMethod("EnsureOccasionalFields");
                FieldInfo controls = occasionalFields.FieldType.GetField("Controls");

                SecurityCritical.ExecutePrivileged(new PermissionSet(PermissionState.Unrestricted), delegate
                {
                    System.Reflection.Emit.DynamicMethod dm = new System.Reflection.Emit.DynamicMethod("get_Controls", typeof(ControlCollection), new Type[] { typeof(Control) }, typeof(Control).Module, true);
                    ILGenerator il = dm.GetILGenerator();
                    Label occFieldsNull = il.DefineLabel();
                    Label retControls = il.DefineLabel();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldfld, occasionalFields);
                    il.Emit(OpCodes.Brfalse_S, occFieldsNull);
                    il.MarkLabel(retControls);
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldfld, occasionalFields);
                    il.Emit(OpCodes.Ldfld, controls);
                    il.Emit(OpCodes.Ret);
                    il.MarkLabel(occFieldsNull);
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Call, ensureOccasionalFields);
                    il.Emit(OpCodes.Br, retControls);
                    handler = (GetControlsDelegate)dm.CreateDelegate(typeof(GetControlsDelegate));
                });
            }
            return handler;
        }
Beispiel #52
0
        private static Func <IServiceFactory, IQuery <TResult>, Task <TResult> > CreateDelegate <TResult>(Type queryType)
        {
            // Define the signature of the dynamic method.
            var dynamicMethod = new System.Reflection.Emit.DynamicMethod("Sql", typeof(Task <TResult>), new[] { typeof(IServiceFactory), typeof(IQuery <TResult>) });

            System.Reflection.Emit.ILGenerator generator = dynamicMethod.GetILGenerator();

            // Create the closed generic query handler type.
            Type queryHandlerType = typeof(IQueryHandler <,>).MakeGenericType(queryType, typeof(TResult));

            // Get the MethodInfo that represents the HandleAsync method.
            MethodInfo method = queryHandlerType.GetMethod("HandleAsync");

            // Push the service factory onto the evaluation stack.
            generator.Emit(OpCodes.Ldarg_0);

            // Push the query handler type onto the evaluation stack.
            generator.Emit(OpCodes.Ldtoken, queryHandlerType);
            generator.Emit(OpCodes.Call, GetTypeFromHandleMethod);

            // Call the GetInstance method and push the query handler
            // instance onto the evaluation stack.
            generator.Emit(OpCodes.Callvirt, GetInstanceMethod);

            // Since the GetInstance method returns an object,
            // we need to cast it to the actual query handler type.
            generator.Emit(OpCodes.Castclass, queryHandlerType);

            // Push the query onto the evaluation stack.
            generator.Emit(OpCodes.Ldarg_1);

            // The query is passed in as an IQuery<TResult> instance
            // and we need to cast it to the actual query type.
            generator.Emit(OpCodes.Castclass, queryType);

            // Call the Sql method and push the Task<TResult>
            // onto the evaluation stack.
            generator.Emit(OpCodes.Callvirt, method);

            // Mark the end of the dynamic method.
            generator.Emit(OpCodes.Ret);

            var getQueryHandlerDelegate =
                dynamicMethod.CreateDelegate(typeof(Func <IServiceFactory, IQuery <TResult>, Task <TResult> >));

            return((Func <IServiceFactory, IQuery <TResult>, Task <TResult> >)getQueryHandlerDelegate);
        }
Beispiel #53
0
        private ConstructorDelegate GetConstructor(string typeName)
        {
            Type            t    = Type.GetType(typeName);
            ConstructorInfo ctor = t.GetConstructor(new Type[0]);

            var methodName = t.Name + "Ctor";

            System.Reflection.Emit.DynamicMethod dm = new System.Reflection.Emit.DynamicMethod(methodName, t, new Type[0], typeof(Activator));
            ILGenerator lgen = dm.GetILGenerator();

            lgen.Emit(OpCodes.Newobj, ctor);
            lgen.Emit(OpCodes.Ret);

            ConstructorDelegate creator = (ConstructorDelegate)dm.CreateDelegate(typeof(ConstructorDelegate));

            return(creator);
        }
Beispiel #54
0
        public static DynamicMemberSetter CreatePropertySetter(PropertyInfo property)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            if (!property.CanWrite)
            {
                return(null);
            }

            MethodInfo setMethod = property.GetSetMethod();

            if (setMethod == null) //maybe is private
            {
                setMethod = property.GetSetMethod(true);
            }

            var dm = new System.Reflection.Emit.DynamicMethod("props", null,
                                                              new[] { typeof(object), typeof(object) },
                                                              property.DeclaringType, true);

            ILGenerator il = dm.GetILGenerator();

            if (!setMethod.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }
            il.Emit(OpCodes.Ldarg_1);

            EmitCastToReference(il, property.PropertyType);
            if (!setMethod.IsStatic && !property.DeclaringType.IsValueType)
            {
                il.EmitCall(OpCodes.Callvirt, setMethod, null);
            }
            else
            {
                il.EmitCall(OpCodes.Call, setMethod, null);
            }

            il.Emit(OpCodes.Ret);

            return((DynamicMemberSetter)dm.CreateDelegate(typeof(DynamicMemberSetter)));
        }
 /// <summary>
 /// Fill the DynamicMethod with a stub.
 /// </summary>
 public static SRE.DynamicMethod Stub(this SRE.DynamicMethod dm)
 {
     SRE.ILGenerator il = dm.GetILGenerator();
     for (int i = 0; i < 32; i++)
     {
         // Prevent mono from inlining the DynamicMethod.
         il.Emit(SRE.OpCodes.Nop);
     }
     if (dm.ReturnType != typeof(void))
     {
         il.DeclareLocal(dm.ReturnType);
         il.Emit(SRE.OpCodes.Ldloca_S, (sbyte)0);
         il.Emit(SRE.OpCodes.Initobj, dm.ReturnType);
         il.Emit(SRE.OpCodes.Ldloc_0);
     }
     il.Emit(SRE.OpCodes.Ret);
     return(dm);
 }
Beispiel #56
0
        public static DynamicMemberGetter CreatePropertyGetter(PropertyInfo property)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            if (!property.CanRead)
            {
                return(null);
            }

            MethodInfo getMethod = property.GetGetMethod();

            if (getMethod == null) //maybe is private
            {
                getMethod = property.GetGetMethod(true);
            }

            var dm = new System.Reflection.Emit.DynamicMethod("propg", typeof(object),
                                                              new[] { typeof(object) },
                                                              property.DeclaringType, true);

            ILGenerator il = dm.GetILGenerator();

            if (!getMethod.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
                il.EmitCall(OpCodes.Callvirt, getMethod, null);
            }
            else
            {
                il.EmitCall(OpCodes.Call, getMethod, null);
            }

            if (property.PropertyType.IsValueType)
            {
                il.Emit(OpCodes.Box, property.PropertyType);
            }

            il.Emit(OpCodes.Ret);

            return((DynamicMemberGetter)dm.CreateDelegate(typeof(DynamicMemberGetter)));
        }
Beispiel #57
0
        static T CreateCaller <T>()
        {
            var sig  = typeof(T).GetTypeInfo().GetMethod("Invoke");
            var prms = sig.GetParameters().Select(p => p.ParameterType).ToArray();


            var dm  = new System.Reflection.Emit.DynamicMethod("Caller", sig.ReturnType, prms, typeof(LocalInterop).GetTypeInfo().Assembly.ManifestModule);
            var gen = dm.GetILGenerator();

            for (var c = 1; c < prms.Length; c++)
            {
                gen.Emit(OpCodes.Ldarg, c);
            }
            gen.Emit(OpCodes.Ldarg_0);
            gen.EmitCalli(OpCodes.Calli, CallingConventions.Standard, sig.ReturnType, prms.Skip(1).ToArray(), null);

            gen.Emit(OpCodes.Ret);
            return((T)(object)dm.CreateDelegate(typeof(T)));
        }
        private int GetSize(string target)
        {
            Type targetType = Type.GetType(target, false);

            if (targetType == null)
            {
                return(-1);
            }

            SRE.DynamicMethod dm = new SRE.DynamicMethod("", typeof(int), null);

            SRE.ILGenerator gen = dm.GetILGenerator();

            gen.Emit(SRE.OpCodes.Sizeof, targetType);
            gen.Emit(SRE.OpCodes.Ret);

            SizeDM del = (SizeDM)dm.CreateDelegate(typeof(SizeDM));

            return(del());
        }
Beispiel #59
0
        public void TestCallingParentsMethod()
        {
            var c = new TestChild();

            Assert.AreEqual("child", c.Test());
            var m = typeof(TestChild).GetMethod("Test").GetBaseDefinition();

            Assert.AreEqual(typeof(TestBase), m.DeclaringType);
            Assert.AreEqual(typeof(TestBase).GetMethod("Test"), m);
            Assert.AreEqual("child", m.Invoke(c, new object[0]));
            Assert.AreEqual("child", ((TestBase)c).Test());

            var dm = new System.Reflection.Emit.DynamicMethod(
                "", typeof(string), new Type[] { typeof(TestBase) }, typeof(YamlNodeTest));

            System.Reflection.Emit.ILGenerator ilgen = dm.GetILGenerator();

            ilgen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            ilgen.Emit(System.Reflection.Emit.OpCodes.Call, typeof(TestBase).GetMethod("Test"));
            ilgen.Emit(System.Reflection.Emit.OpCodes.Ret);
            var callTest = (Call)dm.CreateDelegate(typeof(Call));

            Assert.AreEqual("base", callTest.Invoke(c));
        }
Beispiel #60
0
        public void LeaveDataOnStackBetweenBranches_OldSchool()
        {
            var dm = new System.Reflection.Emit.DynamicMethod("foo", typeof(int), null);
            var il = dm.GetILGenerator();

            System.Reflection.Emit.Label b0 = il.DefineLabel(), b1 = il.DefineLabel(), b2 = il.DefineLabel();
            il.Emit(System.Reflection.Emit.OpCodes.Ldstr, "abc");
            il.Emit(System.Reflection.Emit.OpCodes.Br, b0); // jump to b0 with "abc"

            il.MarkLabel(b1);                               // incoming: 3
            il.Emit(System.Reflection.Emit.OpCodes.Ldc_I4_4);
            il.EmitCall(System.Reflection.Emit.OpCodes.Call, typeof(Math).GetMethod("Max", new[] { typeof(int), typeof(int) }), null);
            il.Emit(System.Reflection.Emit.OpCodes.Br, b2); // jump to b2 with 4

            il.MarkLabel(b0);                               // incoming: "abc"
            il.EmitCall(System.Reflection.Emit.OpCodes.Callvirt, typeof(string).GetProperty("Length").GetGetMethod(), null);
            il.Emit(System.Reflection.Emit.OpCodes.Br, b1); // jump to b1 with 3

            il.MarkLabel(b2);                               // incoming: 4
            il.Emit(System.Reflection.Emit.OpCodes.Ret);
            int i = ((Func <int>)dm.CreateDelegate(typeof(Func <int>)))();

            Assert.AreEqual(4, i);
        }