CreateDelegate() private method

private CreateDelegate ( System delegateType ) : System.Delegate
delegateType System
return System.Delegate
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));
        }
Esempio n. 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);
        }
Esempio n. 3
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;
        }
        /// <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. 5
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));
        }
        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. 7
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. 8
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)));
        }
        /// <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));
        }
Esempio n. 10
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. 11
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. 12
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. 13
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;
        }
        public static Delegate CreateDelegate(Delegate dlg)
        {
            if (dlg == null)
                throw new ArgumentNullException ();
            if (dlg.Target != null)
                throw new ArgumentException ();
            if (dlg.Method == null)
                throw new ArgumentException ();

            get_runtime_types ();

            var ret_type = dlg.Method.ReturnType;
            var param_types = dlg.Method.GetParameters ().Select (x => x.ParameterType).ToArray ();

            var dynamic = new DynamicMethod (Guid.NewGuid ().ToString (), ret_type, param_types, typeof (object), true);
            var ig = dynamic.GetILGenerator ();

            LocalBuilder retval = null;
            if (ret_type != typeof (void))
                retval = ig.DeclareLocal (ret_type);

            ig.Emit (OpCodes.Call, wait_for_bridge_processing_method);

            var label = ig.BeginExceptionBlock ();

            for (int i = 0; i < param_types.Length; i++)
                ig.Emit (OpCodes.Ldarg, i);
            ig.Emit (OpCodes.Call, dlg.Method);

            if (retval != null)
                ig.Emit (OpCodes.Stloc, retval);

            ig.Emit (OpCodes.Leave, label);

            bool  filter = Debugger.IsAttached || !JNIEnv.PropagateExceptions;
            if (filter) {
                ig.BeginExceptFilterBlock ();

                ig.Emit (OpCodes.Call, mono_unhandled_exception_method);
                ig.Emit (OpCodes.Ldc_I4_1);
                ig.BeginCatchBlock (null);
            } else {
                ig.BeginCatchBlock (typeof (Exception));
            }

            ig.Emit (OpCodes.Dup);
            ig.Emit (OpCodes.Call, exception_handler_method);

            if (filter)
                ig.Emit (OpCodes.Throw);

            ig.EndExceptionBlock ();

            if (retval != null)
                ig.Emit (OpCodes.Ldloc, retval);

            ig.Emit (OpCodes.Ret);

            return dynamic.CreateDelegate (dlg.GetType ());
        }
Esempio n. 15
0
        /// <summary>
        /// CreateHandler
        /// </summary>
        /// <param name="type"></param>
        /// <param name="paramsTypes"></param>
        /// <returns></returns>
        private static CreateOjectHandler CreateHandler(Type type, Type[] paramsTypes)
        {
            DynamicMethod method = new DynamicMethod("DynamicCreateOject", typeof(object),
                new Type[] { typeof(object[]) }, typeof(CreateOjectHandler).Module);

            ConstructorInfo constructor = type.GetConstructor(paramsTypes);

            ILGenerator il = method.GetILGenerator();

            for (int i = 0; i < paramsTypes.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldc_I4, i);
                il.Emit(OpCodes.Ldelem_Ref);
                if (paramsTypes[i].IsValueType)
                {
                    il.Emit(OpCodes.Unbox_Any, paramsTypes[i]);
                }
                else
                {
                    il.Emit(OpCodes.Castclass, paramsTypes[i]);
                }
            }
            il.Emit(OpCodes.Newobj, constructor);
            il.Emit(OpCodes.Ret);

            return (CreateOjectHandler)method.CreateDelegate(typeof(CreateOjectHandler));
        }
        public static Func<object[], object> GetFactory(this ConstructorInfo ctor)
        {
            ctor.ThrowIfNull("ctor");

            var type = ctor.DeclaringType;

            var args = ctor.GetParameters();

            var module = type.Module;

            var dynamicMethod = new DynamicMethod("", typeof(object), new Type[] { typeof(object[]) }, module, true);

            var il = dynamicMethod.GetILGenerator();

            il.CheckArgumentLength(args.Length, true);

            il.LoadArguments(args, true);

            il.Emit(OpCodes.Newobj, ctor);

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

            il.Emit(OpCodes.Ret);

            return (Func<object[], object>)dynamicMethod.CreateDelegate(typeof(Func<object[], object>));
        }
        public static Func<object, object> GetGetter(this PropertyInfo property)
        {
            property.ThrowIfNull("property");

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

            var methodInfo = property.GetGetMethod(true);
            if (methodInfo == null) return null;

            var module = methodInfo.DeclaringType.Module;
            var dynamicMethod = new DynamicMethod("", typeof(object), new Type[] { typeof(object) }, module, true);

            var il = dynamicMethod.GetILGenerator();
            if (!methodInfo.IsStatic)
            {
                il.Emit(OpCodes.Ldarg_0);
            }

            il.Call(methodInfo);

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

            return (Func<object, object>)dynamicMethod.CreateDelegate(typeof(Func<object, object>));
        }
        private static Action<IDbCommand, bool> GetBindByNameSetter(Type commandType)
        {
            if (commandType == null) return null;

            Action<IDbCommand, bool> action;
            if (Cache.TryGetValue(commandType, out action)) return action;

            var prop = commandType.GetProperty("BindByName", BindingFlags.Public | BindingFlags.Instance);
            MethodInfo setter;
            if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool)
                && prop.GetIndexParameters().Length == 0 && (setter = prop.GetSetMethod()) != null)
            {
                var methodName = GetOperationName(commandType) + "_BindByName";
                var method = new DynamicMethod(methodName, null, new []{ 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.TryAdd(commandType, action);
            return action;
        }
Esempio n. 19
0
        /// <summary>
        /// Create a new instance from a Type
        /// </summary>
        public static object CreateInstance(Type type)
        {
            try
            {
                CreateObject c = null;

                if (_cacheCtor.TryGetValue(type, out c))
                {
                    return c();
                }
                else
                {
                    if (type.IsClass)
                    {
                        var dynMethod = new DynamicMethod("_", type, null);
                        var il = dynMethod.GetILGenerator();
                        il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
                        il.Emit(OpCodes.Ret);
                        c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
                        _cacheCtor.Add(type, c);
                    }
                    else if (type.IsInterface) // some know interfaces
                    {
                        if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>))
                        {
                            return CreateInstance(GetGenericListOfType(UnderlyingTypeOf(type)));
                        }
                        else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
                        {
                            var k = type.GetGenericArguments()[0];
                            var v = type.GetGenericArguments()[1];
                            return CreateInstance(GetGenericDictionaryOfType(k, v));
                        }
                        else
                        {
                            throw LiteException.InvalidCtor(type);
                        }
                    }
                    else // structs
                    {
                        var dynMethod = new DynamicMethod("_", typeof(object), null);
                        var il = dynMethod.GetILGenerator();
                        var lv = il.DeclareLocal(type);
                        il.Emit(OpCodes.Ldloca_S, lv);
                        il.Emit(OpCodes.Initobj, type);
                        il.Emit(OpCodes.Ldloc_0);
                        il.Emit(OpCodes.Box, type);
                        il.Emit(OpCodes.Ret);
                        c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
                        _cacheCtor.Add(type, c);
                    }

                    return c();
                }
            }
            catch (Exception)
            {
                throw LiteException.InvalidCtor(type);
            }
        }
Esempio n. 20
0
		EvaluationCallback GetNumberCallback(Number number)
		{
			EvaluationCallback callback;
			if (m_numbercallbacks.TryGetValue(number, out callback) == true) return callback;

			DynamicMethod method = new DynamicMethod(String.Empty, typeof(Number), new Type[] { typeof(Object) }, typeof(TreeCompiler));
			ILGenerator generator = method.GetILGenerator();

			switch (number.NumberType)
			{
				case NumberType.Int:
					generator.Emit(OpCodes.Ldc_I4, number.IntValue);
					generator.Emit(OpCodes.Newobj, typeof(Number).GetConstructor(new Type[] { typeof(Int32) }));
					break;

				case NumberType.Float:
					generator.Emit(OpCodes.Ldc_R4, number.FloatValue);
					generator.Emit(OpCodes.Newobj, typeof(Number).GetConstructor(new Type[] { typeof(Single) }));
					break;

				default:
					generator.Emit(OpCodes.Ldloc, generator.DeclareLocal(typeof(Number)).LocalIndex);
					break;
			}

			generator.Emit(OpCodes.Ret);

			callback = (EvaluationCallback)method.CreateDelegate(typeof(EvaluationCallback));
			m_numbercallbacks[number] = callback;

			return callback;
		}
Esempio n. 21
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. 22
0
		/// <summary>
		/// Generates a dynamic action that replicates vanilla functionality
		/// as the types we need are private at compile time.
		/// </summary>
		/// <remarks>
		/// An alternate would be to inject classes that replicate the nested classes in Terraria.Lighting,
		/// and make the nested classes inherit ours. However, that would make me have to maintain extra code
		/// </remarks>
		/// <returns>Action that will process lighting swipe data</returns>
		private static Action<object> GetLightingSwipeMethod()
		{
			var dm = new DynamicMethod("InvokeSwipe", typeof(void), new[] { typeof(object) });
			var processor = dm.GetILGenerator();

			//IL_0000: nop
			//IL_0001: ldarg.0
			//IL_0002: isinst [OTAPI]Terraria.Lighting/LightingSwipeData
			//IL_0007: stloc.0
			//IL_0008: ldloc.0
			//IL_0009: ldfld class [mscorlib]System.Action`1<class [OTAPI]Terraria.Lighting/LightingSwipeData> [OTAPI]Terraria.Lighting/LightingSwipeData::function
			//IL_000e: ldloc.0
			//IL_000f: callvirt instance void class [mscorlib]System.Action`1<class [OTAPI]Terraria.Lighting/LightingSwipeData>::Invoke(!0)
			//IL_0014: nop
			//IL_0015: ret

			var tSwipeData = typeof(global::Terraria.Lighting).GetNestedType("LightingSwipeData");
			var fSwipeData = tSwipeData.GetField("function");

			var swipeData = processor.DeclareLocal(tSwipeData, false);

			processor.Emit(OpCodes.Ldarg_0);
			processor.Emit(OpCodes.Isinst, tSwipeData);
			processor.Emit(OpCodes.Stloc_0);
			processor.Emit(OpCodes.Ldloc_0);
			processor.Emit(OpCodes.Ldfld, fSwipeData);
			processor.Emit(OpCodes.Ldloc_0);
			processor.Emit(OpCodes.Callvirt, fSwipeData.FieldType.GetMethod("Invoke"));
			processor.Emit(OpCodes.Ret);

			return (Action<object>)dm.CreateDelegate(typeof(Action<object>));
		}
        static void Main(string[] args)
        {
            // 2. create an instance of DynamicMethod and specify the method signature
            Type returnType = typeof(Int64);
            Type[] parameterTypes = new Type[] { typeof(Int32) };
            DynamicMethod numberSquaredMethod =
                new DynamicMethod("NumberSquared", returnType, parameterTypes);

            // 3. get the ILGenerator instance
            ILGenerator il = numberSquaredMethod.GetILGenerator();

            //return (Int64)(x*x);

            // 4. emit code using the ILGenerator
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Conv_I8);
            il.Emit(OpCodes.Dup);
            il.Emit(OpCodes.Mul);
            il.Emit(OpCodes.Ret);

            // 5. create a delegate to call the dynamic method
            Squared numberSquared = (Squared)numberSquaredMethod.CreateDelegate(typeof(Squared));

            Console.WriteLine("Result is: {0}", numberSquared(4));
        }
Esempio n. 24
0
        /// <summary>
        /// Creates the default constructor delegate.
        /// </summary>
        /// <param name="type">The type.</param>
        /// <returns>a <see cref="DefaultCreatorDelegate"/></returns>
        /// <exception cref="Exception"><c>Exception</c>.</exception>
        public static DefaultCreatorDelegate CreateDefaultConstructorDelegate(Type type)
        {
            ConstructorInfo constructorInfo = type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
                                                                  null,
                                                                  new Type[0],
                                                                  null);
            if (constructorInfo == null)
            {
                throw new Exception(
                    string.Format(
                        "The type {0} must declare an empty constructor (the constructor may be private, internal, protected, protected internal, or public).",
                        type));
            }

            #if !CompactFramework
            DynamicMethod dynamicMethod = new DynamicMethod("InstantiateObject",
                                                            MethodAttributes.Static | MethodAttributes.Public,
                                                            CallingConventions.Standard,
                                                            typeof(object),
                                                            null,
                                                            type,
                                                            true);
            ILGenerator generator = dynamicMethod.GetILGenerator();
            generator.Emit(OpCodes.Newobj, constructorInfo);
            generator.Emit(OpCodes.Ret);
            return (DefaultCreatorDelegate)dynamicMethod.CreateDelegate(typeof(DefaultCreatorDelegate));
            #else
            return () => constructorInfo.Invoke(null);
            #endif
        }
 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. 26
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. 27
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. 28
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));
        }
        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);
            }
        }
Esempio n. 30
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. 31
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. 32
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. 33
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. 34
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. 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;
        }
Esempio n. 36
0
        private MethodDefinition CreateMethodDefinition()
        {
            var deleg = _dynamicMethod.CreateDelegate(typeof(Invokable), null) as Invokable;

            var resultBody       = new BodyDefinition(deleg);
            var methodDefinition = new MethodDefinition(resultBody);

            return(methodDefinition);
        }
Esempio n. 37
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)));
        }
        /// <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. 40
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)));
        }
        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);
        }
Esempio n. 42
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. 43
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);
        }
Esempio n. 44
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);
        }
        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. 46
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. 47
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)));
        }
Esempio n. 48
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. 49
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. 50
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. 51
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. 52
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. 53
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. 54
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. 55
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)));
        }