GetILGenerator() public method

public GetILGenerator ( ) : System.Reflection.Emit.ILGenerator
return System.Reflection.Emit.ILGenerator
Esempio n. 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));
        }
                 /// <summary>
        /// Initializes a new instance of the <see cref="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));
            }
                     _fieldType = fieldInfo.FieldType;
                     nullInternal = GetNullInternal(_fieldType);

                     // Emit the IL for set access. 
                     DynamicMethod dynamicMethodSet = new DynamicMethod("SetImplementation", null, new Type[] { typeof(object), typeof(object) }, 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));
        }
Esempio n. 3
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)));
        }
Esempio n. 4
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);
        }
Esempio n. 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)));
        }
        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);
            }
        }
        /// <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));
        }
Esempio n. 8
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;
        }
Esempio n. 9
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));
        }
        /// <summary>
        /// Creates a dynamic getter for the property
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <returns></returns>
        public static GenericGetter CreateGetMethod(PropertyInfo propertyInfo)
        {
            /*
             * If there's no getter return null
             */
            MethodInfo getMethod = propertyInfo.GetGetMethod();
            if (getMethod == null)
                return null;

            /*
             * Create the dynamic method
             */
            Type[] arguments = new Type[1];
            arguments[0] = typeof(object);

            DynamicMethod getter = new DynamicMethod(
                String.Concat("_Get", propertyInfo.Name, "_"),
                typeof(object), arguments, propertyInfo.DeclaringType,false);

            ILGenerator generator = getter.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)
                generator.Emit(OpCodes.Box, propertyInfo.PropertyType);

            generator.Emit(OpCodes.Ret);

            /*
             * Create the delegate and return it
             */
            return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
        }
 public static Action GetEntryDelegate(this MethodInfo entryPoint)
 {
     if (!entryPoint.IsPublic || !entryPoint.DeclaringType.IsPublic)
     {
         Log.WriteLine(LogLevel.Error, "Entry point: {0}.{1} is not public. This may cause errors with Mono.",
             entryPoint.DeclaringType.FullName, entryPoint.Name);
     }
     var dm = new DynamicMethod(entryPoint.DeclaringType.Assembly.GetName().Name + "_entrypoint_" + entryPoint.DeclaringType.FullName + entryPoint.Name, null, null, true);
     var il = dm.GetILGenerator();
     var args = entryPoint.GetParameters();
     if (args.Length > 1) throw new ArgumentException("Cannot handle entry points with more than 1 parameter.");
     if (args.Length == 1)
     {
         if (args[0].ParameterType != typeof(string[])) throw new ArgumentException("Entry point paramter must be a string array.");
         il.Emit(OpCodes.Ldc_I4_0);
         il.Emit(OpCodes.Newarr, typeof(string));
     }
     il.EmitCall(OpCodes.Call, entryPoint, null);
     if (entryPoint.ReturnType != typeof(void))
     {
         il.Emit(OpCodes.Pop);
     }
     il.Emit(OpCodes.Ret);
     return (Action)dm.CreateDelegate(typeof(Action));
 }
Esempio n. 12
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));
		}
Esempio n. 13
0
        //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));
        }
Esempio n. 14
0
        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;
        }
Esempio n. 15
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>));
			}
		}
Esempio n. 16
0
 private void GenerateMethodBody(DynamicMethod method, Operation operation)
 {
     ILGenerator generator = method.GetILGenerator();
     generator.DeclareLocal(typeof(double));
     GenerateMethodBody(generator, operation);
     generator.Emit(OpCodes.Ret);
 }
        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;
        }
Esempio n. 18
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));
		}
Esempio n. 19
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));
        }
Esempio n. 20
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));
 }
Esempio n. 21
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));
        }
        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);
        }
Esempio n. 23
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);
		}          
Esempio n. 24
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));
    }
Esempio n. 25
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;
            }
        }
Esempio n. 26
0
        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;
        }
Esempio n. 27
0
        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));
        }
Esempio n. 28
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;
        }
Esempio n. 29
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() }));
        }
Esempio n. 30
0
 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;
 }
Esempio n. 31
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);
 }
Esempio n. 32
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;
        }
Esempio n. 33
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
		}
Esempio n. 34
0
        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));
        }
Esempio n. 35
0
        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);
        }
Esempio n. 36
0
        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);
            });
        }
Esempio n. 37
0
		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);
		}
Esempio n. 38
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);
        }
Esempio n. 39
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();
        }
Esempio n. 40
0
        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);
        }
        /// <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)));
        }
Esempio n. 42
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)));
        }
Esempio n. 44
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)));
        }
Esempio n. 45
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 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;
        }
Esempio n. 47
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);
        }
Esempio n. 48
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);
        }
Esempio n. 49
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);
 }
Esempio n. 51
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)));
        }
Esempio n. 52
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)));
        }
Esempio n. 53
0
        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());
        }
Esempio n. 54
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));
        }
Esempio n. 55
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);
        }
Esempio n. 56
0
        public static DynamicMemberMethod CreateMethod(MethodInfo method)
        {
            ParameterInfo[] pi = method.GetParameters();

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

            ILGenerator il = dm.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);

            for (int index = 0; index < pi.Length; index++)
            {
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Ldc_I4, index);

                Type parameterType = pi[index].ParameterType;
                if (parameterType.IsByRef)
                {
                    parameterType = parameterType.GetElementType();
                    if (parameterType.IsValueType)
                    {
                        il.Emit(OpCodes.Ldelem_Ref);
                        il.Emit(OpCodes.Unbox, parameterType);
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldelema, parameterType);
                    }
                }
                else
                {
                    il.Emit(OpCodes.Ldelem_Ref);

                    if (parameterType.IsValueType)
                    {
                        il.Emit(OpCodes.Unbox, parameterType);
                        il.Emit(OpCodes.Ldobj, parameterType);
                    }
                }
            }

            if ((method.IsAbstract || method.IsVirtual) &&
                !method.IsFinal && !method.DeclaringType.IsSealed)
            {
                il.Emit(OpCodes.Callvirt, method);
            }
            else
            {
                il.Emit(OpCodes.Call, method);
            }

            if (method.ReturnType == typeof(void))
            {
                il.Emit(OpCodes.Ldnull);
            }
            else if (method.ReturnType.IsValueType)
            {
                il.Emit(OpCodes.Box, method.ReturnType);
            }
            il.Emit(OpCodes.Ret);

            return((DynamicMemberMethod)dm.CreateDelegate(typeof(DynamicMemberMethod)));
        }
Esempio n. 57
0
        /// <summary>
        /// Compiles a function that copies fields with the same name and type from one object to the other.
        /// Be sure to only compile a single function for a set of types and re-use it, because this is slow and the function does not get garbage collected, but extremely fast after compiled.
        /// </summary>
        public static CopyIntoDelegate <T, S> GetShallowFieldCopier <T, S>()
        {
            if (RCCache_Copiers <T, S> .ShallowFieldCopier is null)
            {
                lock (RCCache_Copiers <T, S> .Lock) {
                    if (RCCache_Copiers <T, S> .ShallowFieldCopier != null)
                    {
                        return(RCCache_Copiers <T, S> .ShallowFieldCopier);
                    }
                    RCCache_Copiers <T, S> .ShallowFieldCopier = (CopyIntoDelegate <T, S>)CreateDelegate();
                }
            }
            return(RCCache_Copiers <T, S> .ShallowFieldCopier);

            Delegate CreateDelegate()
            {
                Type targetType = typeof(T);
                Type srcType    = typeof(S);

                BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

                FieldInfo[] targetFields = targetType.GetFields(flags);
                FieldInfo[] srcFields    = targetType == srcType ? targetFields : srcType.GetFields(flags);

                DynamicMethod dynmethod = new System.Reflection.Emit.DynamicMethod("ShallowFieldCopy", typeof(void), new Type[2] {
                    targetType, srcType
                }, true);
                ILGenerator gen = dynmethod.GetILGenerator();

                foreach (FieldInfo targetField in targetFields)
                {
                    FieldInfo srcField = targetType == srcType ? targetField : srcFields.FirstOrDefault(f => f.Name.EqIgCase(targetField.Name));
                    if (srcField is null)
                    {
                        continue;
                    }

                    if (targetField.FieldType == srcField.FieldType)
                    {
                        gen.Emit(OpCodes.Ldarg_0);
                        gen.Emit(OpCodes.Ldarg_1);
                        gen.Emit(OpCodes.Ldfld, srcField);
                        gen.Emit(OpCodes.Stfld, targetField);
                    }
                    else
                    {
                        TypeConverter converter      = targetField.FieldType.GetTypeConverter();
                        FieldInfo     converterField = GetStaticConverterFieldByConverter(converter);
                        if (converterField != null && converter.CanConvertFrom(srcField.FieldType))
                        {
                            gen.Emit(OpCodes.Ldarg_0);
                            gen.Emit(OpCodes.Ldsfld, converterField);
                            gen.Emit(OpCodes.Ldarg_1);
                            gen.Emit(OpCodes.Ldfld, srcField);
                            gen.Emit(OpCodes.Box, srcField.FieldType);
                            gen.Emit(OpCodes.Callvirt, converter.GetType().GetMethod(nameof(TypeConverter.ConvertFrom), new Type[] { typeof(object) }));
                            gen.Emit(OpCodes.Unbox_Any, targetField.FieldType);
                            gen.Emit(OpCodes.Stfld, targetField);
                        }
                    }
                }
                gen.Emit(OpCodes.Ret);
                return(dynmethod.CreateDelegate(typeof(CopyIntoDelegate <T, S>)));
            }
        }
Esempio n. 58
0
 public int GetTokenFor(string literal)
 {
     return(method.GetILGenerator().TokenGenerator.GetToken(literal));
 }
Esempio n. 59
0
        public EvalDelegate CreateDelegate()
        {
            var type = module.Find(evalClassName, isReflectionName: true);

            Debug.Assert(type != null);
            var method = type?.FindMethod(evalMethodName);

            Debug.Assert(method?.Body != null);
            if (!(method?.Body is CilBody body))
            {
                return(null);
            }
            if (method.ReturnType.ElementType != ElementType.Boolean)
            {
                return(null);
            }
            if (body.HasExceptionHandlers)
            {
                return(null);
            }

            Debug.Assert(method.MethodSig.Params.Count == evalDelegateParamTypes.Length);
            if (method.MethodSig.Params.Count != evalDelegateParamTypes.Length)
            {
                return(null);
            }
            var dm  = new SRE.DynamicMethod("compiled filter expr", typeof(bool), evalDelegateParamTypes, typeof(FilterExpressionMethods), skipVisibility: false);
            var ilg = dm.GetILGenerator();

            var labelsDict = new Dictionary <Instruction, SRE.Label>();
            var instrs     = body.Instructions;

            for (int i = 0; i < instrs.Count; i++)
            {
                var instr = instrs[i];
                switch (instr.Operand)
                {
                case Instruction targetInstr:
                    if (!labelsDict.ContainsKey(targetInstr))
                    {
                        labelsDict.Add(targetInstr, ilg.DefineLabel());
                    }
                    break;

                case IList <Instruction> targetInstrs:
                    foreach (var targetInstr in targetInstrs)
                    {
                        if (!labelsDict.ContainsKey(targetInstr))
                        {
                            labelsDict.Add(targetInstr, ilg.DefineLabel());
                        }
                    }
                    break;
                }
            }

            Dictionary <Local, SRE.LocalBuilder> localsDict = null;

            if (body.Variables.Count > 0)
            {
                localsDict = new Dictionary <Local, SRE.LocalBuilder>(body.Variables.Count);
                foreach (var local in body.Variables)
                {
                    var lb = ilg.DeclareLocal(Import(local.Type), local.Type.IsPinned);
                    if (local.Index != lb.LocalIndex)
                    {
                        return(null);
                    }
                    if (local.Name != null)
                    {
                        lb.SetLocalSymInfo(local.Name);
                    }
                    localsDict.Add(local, lb);
                }
            }

            foreach (var instr in body.Instructions)
            {
                if (labelsDict.TryGetValue(instr, out var label))
                {
                    ilg.MarkLabel(label);
                }
                if (!toReflectionOpCode.TryGetValue(instr.OpCode, out var sreOpCode))
                {
                    return(null);
                }
                switch (instr.OpCode.OperandType)
                {
                case OperandType.InlineBrTarget:
                case OperandType.ShortInlineBrTarget:
                    var targetInstr = (Instruction)instr.Operand;
                    ilg.Emit(sreOpCode, labelsDict[targetInstr]);
                    break;

                case OperandType.InlineSwitch:
                    var targets    = (IList <Instruction>)instr.Operand;
                    var newTargets = new SRE.Label[targets.Count];
                    for (int i = 0; i < newTargets.Length; i++)
                    {
                        newTargets[i] = labelsDict[targets[i]];
                    }
                    ilg.Emit(sreOpCode, newTargets);
                    break;

                case OperandType.InlineNone:
                    ilg.Emit(sreOpCode);
                    break;

                case OperandType.InlineI:
                    ilg.Emit(sreOpCode, (int)instr.Operand);
                    break;

                case OperandType.InlineI8:
                    ilg.Emit(sreOpCode, (long)instr.Operand);
                    break;

                case OperandType.InlineR:
                    ilg.Emit(sreOpCode, (double)instr.Operand);
                    break;

                case OperandType.ShortInlineR:
                    ilg.Emit(sreOpCode, (float)instr.Operand);
                    break;

                case OperandType.ShortInlineI:
                    if (instr.OpCode.Code == Code.Ldc_I4_S)
                    {
                        ilg.Emit(sreOpCode, (sbyte)instr.Operand);
                    }
                    else
                    {
                        ilg.Emit(sreOpCode, (byte)instr.Operand);
                    }
                    break;

                case OperandType.InlineString:
                    ilg.Emit(sreOpCode, (string)instr.Operand);
                    break;

                case OperandType.InlineVar:
                case OperandType.ShortInlineVar:
                    Parameter p;
                    switch (instr.OpCode.Code)
                    {
                    case Code.Ldarg:
                    case Code.Ldarga:
                    case Code.Starg:
                        p = (Parameter)instr.Operand;
                        if (p.Index > ushort.MaxValue)
                        {
                            return(null);
                        }
                        ilg.Emit(sreOpCode, (short)p.Index);
                        break;

                    case Code.Ldarg_S:
                    case Code.Ldarga_S:
                    case Code.Starg_S:
                        p = (Parameter)instr.Operand;
                        if (p.Index > byte.MaxValue)
                        {
                            return(null);
                        }
                        ilg.Emit(sreOpCode, (byte)p.Index);
                        break;

                    case Code.Ldloc:
                    case Code.Ldloca:
                    case Code.Stloc:
                    case Code.Ldloc_S:
                    case Code.Ldloca_S:
                    case Code.Stloc_S:
                        ilg.Emit(sreOpCode, localsDict[(Local)instr.Operand]);
                        break;

                    default:
                        return(null);
                    }
                    break;

                case OperandType.InlineMethod:
                    var m = Import((IMethod)instr.Operand);
                    if (m is SR.ConstructorInfo ci)
                    {
                        ilg.Emit(sreOpCode, ci);
                    }
                    else
                    {
                        ilg.Emit(sreOpCode, (SR.MethodInfo)m);
                    }
                    break;

                case OperandType.InlineTok:
                case OperandType.InlineType:
                case OperandType.InlineField:
                case OperandType.InlinePhi:
                case OperandType.InlineSig:
                default:
                    return(null);
                }
            }

            return((EvalDelegate)dm.CreateDelegate(typeof(EvalDelegate)));
        }