System.Reflection.Emit.DynamicMethod.GetILGenerator()

Here are the examples of the csharp api System.Reflection.Emit.DynamicMethod.GetILGenerator() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

538 Examples 7

19 View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : alelievr

public static Delegate CreateGenericSetterDelegate(Type childType, FieldInfo field)
		{
			//Create the delegate type that takes our node type in parameter
			var delegateType = typeof(ChildFieldSetter<,>).MakeGenericType(new Type[] { childType, field.FieldType });

			//Get the child field from base clreplaced
			FieldInfo fi = childType.GetField(field.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);

			#if NET_4_6
				ParameterExpression targetExp = Expression.Parameter(childType, "target");
				ParameterExpression valueExp = Expression.Parameter(fi.FieldType, "value");

				// Expression.Property can be used here as well
				MemberExpression fieldExp = Expression.Field(targetExp, fi);
				BinaryExpression replacedignExp = Expression.replacedign(fieldExp, valueExp);

				return Expression.Lambda(delegateType, replacedignExp, targetExp, valueExp).Compile();
			#else
				//Create a new method which return the field fi
				DynamicMethod dm = new DynamicMethod("Set" + fi.Name, typeof(object), new Type[] { childType, typeof(object) }, true);
				ILGenerator il = dm.GetILGenerator();
				// Load the instance of the object (argument 0) and the replacing value onto the stack
				il.Emit(OpCodes.Ldarg_0);
				il.Emit(OpCodes.Ldarg_1);
				if (fi.FieldType.IsValueType)
					il.Emit(OpCodes.Unbox_Any, fi.FieldType);
				// Set the value of the field to the value on top of the stack
				il.Emit(OpCodes.Stfld, fi);
				il.Emit(OpCodes.Ret);
	
				return dm.CreateDelegate(delegateType);
			#endif
		}

19 View Source File : CommandDefinition.cs
License : MIT License
Project Creator : anet-team

private static Action<IDbCommand> GetInit(Type commandType)
        {
            if (commandType == null)
                return null; // GIGO
            if (SqlMapper.Link<Type, Action<IDbCommand>>.TryGet(commandInitCache, commandType, out Action<IDbCommand> action))
            {
                return action;
            }
            var bindByName = GetBasicPropertySetter(commandType, "BindByName", typeof(bool));
            var initialLongFetchSize = GetBasicPropertySetter(commandType, "InitialLONGFetchSize", typeof(int));

            action = null;
            if (bindByName != null || initialLongFetchSize != null)
            {
                var method = new DynamicMethod(commandType.Name + "_init", null, new Type[] { typeof(IDbCommand) });
                var il = method.GetILGenerator();

                if (bindByName != null)
                {
                    // .BindByName = true
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Castclreplaced, commandType);
                    il.Emit(OpCodes.Ldc_I4_1);
                    il.EmitCall(OpCodes.Callvirt, bindByName, null);
                }
                if (initialLongFetchSize != null)
                {
                    // .InitialLONGFetchSize = -1
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Castclreplaced, commandType);
                    il.Emit(OpCodes.Ldc_I4_M1);
                    il.EmitCall(OpCodes.Callvirt, initialLongFetchSize, null);
                }
                il.Emit(OpCodes.Ret);
                action = (Action<IDbCommand>)method.CreateDelegate(typeof(Action<IDbCommand>));
            }
            // cache it
            SqlMapper.Link<Type, Action<IDbCommand>>.TryAdd(ref commandInitCache, commandType, ref action);
            return action;
        }

19 View Source File : TypedReferenceHelpers.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static Set BuildSetHelper(Type refType)
        {
            var dm = new DynamicMethod("", typeof(void), new[] {typeof(object), typeof(TypedRefPtr)}, Unverifier.Module, true);
            var gen = dm.GetILGenerator();

            gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, 1);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldfld, typedPtrField);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldobj, typeof(TypedReference));
            gen.Emit(System.Reflection.Emit.OpCodes.Refanyval, refType);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            gen.Emit(System.Reflection.Emit.OpCodes.Unbox_Any, refType);
            gen.Emit(System.Reflection.Emit.OpCodes.Stobj, refType);
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

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

19 View Source File : DynamicReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
        {
            DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType);
            ILGenerator generator = dynamicMethod.GetILGenerator();

            GenerateCreateSetPropertyIL(propertyInfo, generator);

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

19 View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Func<TArg, TRes> CreateFunc<TArg, TRes>(TypeInfo callInfo, string methodName, TypeInfo argInfo, TypeInfo resInfo)
        {
            ConstructorInfo constructor = callInfo.GetConstructor(Type.EmptyTypes);
            if (constructor == (ConstructorInfo)null)
                throw new ArgumentException("类型" + callInfo.FullName + "没有无参构造函数");
            MethodInfo method = callInfo.GetMethod(methodName);
            if (method == (MethodInfo)null)
                throw new ArgumentException("类型" + callInfo.FullName + "没有名称为" + methodName + "的方法");
            if (method.ReturnType != (Type)resInfo)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "返回值不为" + resInfo.FullName);
            ParameterInfo[] parameters = method.GetParameters();
            if (parameters.Length != 1)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "参数不是一个");
            if (parameters[0].ParameterType != (Type)argInfo)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "唯一参数不为" + argInfo.FullName);
            DynamicMethod dynamicMethod = new DynamicMethod(methodName, typeof(TRes), new Type[1]
            {
        typeof (TArg)
            });
            ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
            ilGenerator.Emit(OpCodes.Nop);
            ilGenerator.Emit(OpCodes.Ldarg, 0);
            ilGenerator.Emit(OpCodes.Castclreplaced, (Type)argInfo);
            LocalBuilder local1 = ilGenerator.DeclareLocal((Type)argInfo);
            ilGenerator.Emit(OpCodes.Stloc, local1);
            ilGenerator.Emit(OpCodes.Newobj, constructor);
            LocalBuilder local2 = ilGenerator.DeclareLocal((Type)callInfo);
            ilGenerator.Emit(OpCodes.Stloc, local2);
            ilGenerator.Emit(OpCodes.Ldloc, local2);
            ilGenerator.Emit(OpCodes.Ldloc, local1);
            ilGenerator.Emit(OpCodes.Callvirt, method);
            LocalBuilder local3 = ilGenerator.DeclareLocal(method.ReturnType);
            ilGenerator.Emit(OpCodes.Stloc, local3);
            ilGenerator.Emit(OpCodes.Ldloc, local3);
            ilGenerator.Emit(OpCodes.Castclreplaced, (Type)typeof(TRes).GetTypeInfo());
            LocalBuilder local4 = ilGenerator.DeclareLocal((Type)resInfo);
            ilGenerator.Emit(OpCodes.Stloc, local4);
            ilGenerator.Emit(OpCodes.Ldloc, local4);
            ilGenerator.Emit(OpCodes.Ret);
            return dynamicMethod.CreateDelegate(typeof(Func<TArg, TRes>)) as Func<TArg, TRes>;
        }

19 View Source File : DirectCall.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static TypedInvocation GetTypedInvocationProxy(MethodBase method, OpCode opCode, Type constrainType)
        {
            Hashtable table;
            object key;
            if(constrainType == null)
            {
                key = new KeyValuePair<MethodBase, OpCode>(method, opCode);
                table = typedProxies;
            }
            else
            {
                key = new KeyValuePair<MethodBase, Type>(method, constrainType);
                table = constrainedProxies;
            }

            var proxy = (TypedInvocation) table[key];
            if(proxy != null)
                return proxy;

            lock(typedProxies)
            {
                proxy = (TypedInvocation) table[key];
                if(proxy != null)
                    return proxy;

                var parameters = method.GetParameters();
                Type[] paramTypes;
                if(opCode != System.Reflection.Emit.OpCodes.Newobj)
                {
                    paramTypes = new Type[parameters.Length + (method.IsStatic ? 0 : 1) + 1];
                    for(var i = 0; i < paramTypes.Length - 1; i++)
                        if(method.IsStatic)
                        {
                            paramTypes[i] = parameters[i].ParameterType;
                        }
                        else
                        {
                            if(i == 0)
                                if(constrainType != null)
                                    paramTypes[0] = constrainType.MakeByRefType();
                                else if(method.DeclaringType.IsValueType)
                                    paramTypes[0] = method.DeclaringType.MakeByRefType();
                                else
                                    paramTypes[0] = method.DeclaringType;
                            else
                                paramTypes[i] = parameters[i - 1].ParameterType;
                        }
                }
                else
                {
                    paramTypes = new Type[parameters.Length + 1];
                    for(var i = 0; i < paramTypes.Length - 1; i++) paramTypes[i] = parameters[i].ParameterType;
                }

                var retType = method is MethodInfo ? ((MethodInfo) method).ReturnType : typeof(void);
                if(opCode == System.Reflection.Emit.OpCodes.Newobj)
                    retType = method.DeclaringType;
                var dm = new DynamicMethod("", typeof(object), new[] {typeof(DarksVMContext), typeof(IReference[]), typeof(Type[])},
                    Unverifier.Module, true);
                var gen = dm.GetILGenerator();

                for(var i = 0; i < paramTypes.Length - 1; i++)
                {
                    var paramType = paramTypes[i];
                    var isByRef = paramType.IsByRef;
                    if(isByRef)
                        paramType = paramType.GetElementType();

                    var typedRefLocal = gen.DeclareLocal(typeof(TypedReference));
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);

                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, typedRefLocal);

                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);

                    gen.Emit(System.Reflection.Emit.OpCodes.Callvirt, refToTypedRef);

                    gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, typedRefLocal);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldelem_Ref);
                    gen.Emit(System.Reflection.Emit.OpCodes.Call, castTypedRef);

                    gen.Emit(System.Reflection.Emit.OpCodes.Ldloc, typedRefLocal);
                    gen.Emit(System.Reflection.Emit.OpCodes.Refanyval, paramType);

                    if(!isByRef)
                        gen.Emit(System.Reflection.Emit.OpCodes.Ldobj, paramType);
                }

                if(constrainType != null)
                    gen.Emit(System.Reflection.Emit.OpCodes.Constrained, constrainType);

                if(method is MethodInfo)
                    gen.Emit(opCode, (MethodInfo) method);
                else
                    gen.Emit(opCode, (ConstructorInfo) method);

                if(retType.IsByRef)
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, retType.GetElementType());
                    gen.Emit(System.Reflection.Emit.OpCodes.Newobj, newTypedRef);
                }
                else if(retType == typeof(void))
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldnull);
                }
                else if(retType.IsValueType)
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Box, retType);
                }

                gen.Emit(System.Reflection.Emit.OpCodes.Ret);

                proxy = (TypedInvocation) dm.CreateDelegate(typeof(TypedInvocation));
                table[key] = proxy;
                return proxy;
            }
        }

19 View Source File : MSILGenerator.cs
License : MIT License
Project Creator : aloneguid

public PopulateListDelegate GenerateCollector(Type clreplacedType, DataField field)
      {
         Type[] methodArgs = { typeof(object), typeof(object), typeof(object), typeof(int) };

         TypeInfo ti = clreplacedType.GetTypeInfo();
         PropertyInfo pi = ti.GetDeclaredProperty(field.ClrPropName ?? field.Name);
         MethodInfo getValueMethod = pi.GetMethod;

         MethodInfo addToListMethod = typeof(List<>).MakeGenericType(field.ClrNullableIfHasNullsType).GetTypeInfo().GetDeclaredMethod("Add");
         MethodInfo addRepLevelMethod = typeof(List<int>).GetTypeInfo().GetDeclaredMethod("Add");

         var runMethod = new DynamicMethod(
            $"Get{clreplacedType.Name}{field.Path}",
            typeof(object),
            methodArgs,
            GetType().GetTypeInfo().Module);

         TypeConversion conversion = GetConversion(pi.PropertyType, field.ClrNullableIfHasNullsType);

         ILGenerator il = runMethod.GetILGenerator();

         GenerateCollector(il, clreplacedType,
            field,
            getValueMethod,
            addToListMethod,
            addRepLevelMethod,
            conversion);

         return (PopulateListDelegate)runMethod.CreateDelegate(typeof(PopulateListDelegate));
      }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : ad313

private static Func<object, Dictionary<string, object>> CreateDictionaryGenerator(Type type)
        {
            var dm = new DynamicMethod($"Dictionary{Guid.NewGuid()}", typeof(Dictionary<string, object>), new[] { typeof(object) }, type, true);
            ILGenerator il = dm.GetILGenerator();
            il.DeclareLocal(typeof(Dictionary<string, object>));
            il.Emit(OpCodes.Nop);
            il.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(Type.EmptyTypes));
            il.Emit(OpCodes.Stloc_0);

            foreach (var item in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                string columnName = item.Name;
                il.Emit(OpCodes.Nop);
                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldstr, columnName);
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Callvirt, item.GetGetMethod());
                if (item.PropertyType.IsValueType)
                {
                    il.Emit(OpCodes.Box, item.PropertyType);
                }
                il.Emit(OpCodes.Callvirt, typeof(Dictionary<string, object>).GetMethod("Add"));
            }
            il.Emit(OpCodes.Nop);

            il.Emit(OpCodes.Ldloc_0);
            il.Emit(OpCodes.Ret);
            return (Func<object, Dictionary<string, object>>)dm.CreateDelegate(typeof(Func<object, Dictionary<string, object>>));
        }

19 View Source File : ReflectionHandlerFactory.cs
License : MIT License
Project Creator : aquilahkj

private static SetValueHandler CreateFieldSetHandler(FieldInfo field)
        {
            var method = new DynamicMethod("", null, new[] {typeof(object), typeof(object)}, field.DeclaringType);
            var iLGenerator = method.GetILGenerator();
            iLGenerator.Emit(OpCodes.Ldarg_0);
            iLGenerator.Emit(OpCodes.Ldarg_1);
            EmitCastToReference(iLGenerator, field.FieldType);
            iLGenerator.Emit(OpCodes.Stfld, field);
            iLGenerator.Emit(OpCodes.Ret);
            return (SetValueHandler) method.CreateDelegate(typeof(SetValueHandler));
        }

19 View Source File : DarksVMTrampoline.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static DynamicMethod CreateTrampolineNormal(int moduleId, ulong codeAdr, uint key, DarksVMFuncSig sig, uint sigId)
        {
            var dm = new DynamicMethod("", sig.RetType, sig.ParamTypes, Unverifier.Module, true);

            var gen = dm.GetILGenerator();
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, moduleId);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I8, (long) codeAdr);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int) key);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int) sigId);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, sig.ParamTypes.Length);
            gen.Emit(System.Reflection.Emit.OpCodes.Newarr, typeof(object));
            for(var i = 0; i < sig.ParamTypes.Length; i++)
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Dup);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldarg, i);
                if(sig.ParamTypes[i].IsValueType)
                    gen.Emit(System.Reflection.Emit.OpCodes.Box, sig.ParamTypes[i]);
                gen.Emit(System.Reflection.Emit.OpCodes.Stelem_Ref);
            }

            gen.Emit(System.Reflection.Emit.OpCodes.Call, entryStubNormal);

            if(sig.RetType == typeof(void))
                gen.Emit(System.Reflection.Emit.OpCodes.Pop);
            else if(sig.RetType.IsValueType)
                gen.Emit(System.Reflection.Emit.OpCodes.Unbox_Any, sig.RetType);
            else
                gen.Emit(System.Reflection.Emit.OpCodes.Castclreplaced, sig.RetType);

            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

            return dm;
        }

19 View Source File : DynamicReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override Func<T> CreateDefaultConstructor<T>(Type type)
        {
            DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), ReflectionUtils.EmptyTypes, type);
            dynamicMethod.InitLocals = true;
            ILGenerator generator = dynamicMethod.GetILGenerator();

            GenerateCreateDefaultConstructorIL(type, generator);

            return (Func<T>)dynamicMethod.CreateDelegate(typeof(Func<T>));
        }

19 View Source File : DynamicReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
        {
            DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType);
            ILGenerator generator = dynamicMethod.GetILGenerator();

            GenerateCreateGetPropertyIL(propertyInfo, generator);

            return (Func<T, object>)dynamicMethod.CreateDelegate(typeof(Func<T, object>));
        }

19 View Source File : TypedReferenceHelpers.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static Cast BuildCastHelper(Type sourceType, Type targetType)
        {
            var dm = new DynamicMethod("", typeof(void), new[] {typeof(TypedRefPtr)}, Unverifier.Module, true);
            var gen = dm.GetILGenerator();

            gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, 0);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldfld, typedPtrField);
            gen.Emit(System.Reflection.Emit.OpCodes.Dup);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldobj, typeof(TypedReference));
            gen.Emit(System.Reflection.Emit.OpCodes.Refanyval, sourceType);
            gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, targetType);
            gen.Emit(System.Reflection.Emit.OpCodes.Stobj, typeof(TypedReference));
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);
            return (Cast) dm.CreateDelegate(typeof(Cast));
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : albahari

public static Func<object, object> GenDynamicProp (PropertyInfo prop)
		{
			//return x => prop.GetValue (x);
			DynamicMethod dynMeth;
			if (prop.DeclaringType.IsInterface)
				dynMeth = new DynamicMethod ("", typeof (object), new[] { typeof (object) });
			else
				dynMeth = new DynamicMethod ("", typeof (object), new[] { typeof (object) }, prop.DeclaringType);
			ILGenerator gen = dynMeth.GetILGenerator ();
			gen.Emit (OpCodes.Ldarg_0);

			if (prop.DeclaringType.IsValueType)
			{
				gen.DeclareLocal (prop.DeclaringType);
				gen.Emit (OpCodes.Unbox_Any, prop.DeclaringType);
				gen.Emit (OpCodes.Stloc_0);
				gen.Emit (OpCodes.Ldloca_S, 0);
				gen.Emit (OpCodes.Call, prop.GetGetMethod (true));
			}
			else
			{
				gen.Emit (OpCodes.Castclreplaced, prop.DeclaringType);
				gen.Emit (OpCodes.Callvirt, prop.GetGetMethod (true));
			}
			if (prop.PropertyType.IsValueType) gen.Emit (OpCodes.Box, prop.PropertyType);
			gen.Emit (OpCodes.Ret);
			return (Func<object, object>)dynMeth.CreateDelegate (typeof (Func<object, object>));
		}

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

private static Action<object, IDbCommand> AddParametersIL(object param, IDbCommand cmd)
        {
            Type pType = param.GetType();
            Type[] args = { typeof(object), typeof(IDbCommand) };

            DynamicMethod method = new DynamicMethod("DynamicAddParam" + Guid.NewGuid().ToString(), null, args, typeof(ParameterCache).Module, true);
            ILGenerator il = method.GetILGenerator();

            foreach (PropertyInfo property in pType.GetProperties())
            {
                il.Emit(OpCodes.Ldarg_1);//load the idbcommand. Loads the argument at index 0 onto the evaluation stack.

                //name
                il.Emit(OpCodes.Ldstr, property.Name);

                //dbtype
                //dynamic property will always return System.Object as property type. Get Type from the value
                Type type = GetTypeOfDynamicProperty(property, param);
                    
                if (type.IsEnum) type = Enum.GetUnderlyingType(type);

                if(TypeCache.TypeToDbType.TryGetValue(type, out DbType dbType))
                    il.Emit(OpCodes.Ldc_I4_S, (byte)dbType);
                else
                    il.Emit(OpCodes.Ldc_I4_S, (byte)DbType.String); //TODO: fix when unkown type

                //value
                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Callvirt, property.GetMethod);

                //box if value type
                if (property.PropertyType.IsValueType)
                    il.Emit(OpCodes.Box, property.PropertyType);

                il.Emit(OpCodes.Call, addInParameter);

                il.Emit(OpCodes.Nop);
            }
            il.Emit(OpCodes.Ret);

            var actionType = System.Linq.Expressions.Expression.GetActionType(typeof(object), typeof(IDbCommand));
            return (Action<object, IDbCommand>)method.CreateDelegate(actionType);
        }

19 View Source File : EmitMemberAccessor.cs
License : MIT License
Project Creator : AllocZero

private static DynamicMethod CreatePropertyGetter(PropertyInfo propertyInfo, Type runtimePropertyType)
        {
            MethodInfo? realMethod = propertyInfo.GetMethod;
            Debug.replacedert(realMethod != null);

            Type? declaringType = propertyInfo.DeclaringType;
            Debug.replacedert(declaringType != null);

            Type declaredPropertyType = propertyInfo.PropertyType;

            DynamicMethod dynamicMethod = CreateGetterMethod(propertyInfo.Name, runtimePropertyType);
            ILGenerator generator = dynamicMethod.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);

            if (declaringType.IsValueType)
            {
                generator.Emit(OpCodes.Unbox, declaringType);
                generator.Emit(OpCodes.Call, realMethod);
            }
            else
            {
                generator.Emit(OpCodes.Castclreplaced, declaringType);
                generator.Emit(OpCodes.Callvirt, realMethod);
            }

            // declaredPropertyType: Type of the property
            // runtimePropertyType:  <T> of JsonConverter / JsonPropertyInfo

            if (declaredPropertyType != runtimePropertyType && declaredPropertyType.IsValueType)
            {
                generator.Emit(OpCodes.Box, declaredPropertyType);
            }

            generator.Emit(OpCodes.Ret);

            return dynamicMethod;
        }

19 View Source File : TypedReferenceHelpers.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static Make BuildMakeHelper(Type targetType)
        {
            var dm = new DynamicMethod("", typeof(void), new[] {typeof(void*), typeof(TypedRefPtr)}, Unverifier.Module, true);
            var gen = dm.GetILGenerator();

            gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, 1);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldfld, typedPtrField);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, targetType);
            gen.Emit(System.Reflection.Emit.OpCodes.Stobj, typeof(TypedReference));
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

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

19 View Source File : Accessor.cs
License : MIT License
Project Creator : andruzzzhka

private static Accessor MakeAccessor(string fieldName)
        {
            var field = typeof(T).GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            if (field == null)
                throw new MissingFieldException(typeof(T).Name, fieldName);

            var dynMethodName = $"<>_accessor__{fieldName}";
            // unfortunately DynamicMethod doesn't like having a ByRef return type, so reflection it
            var dyn = new DynamicMethod(dynMethodName, typeof(U), new[] { typeof(T).MakeByRefType() }, typeof(FieldAccessor<T, U>), true);
            ReflectionUtil.DynamicMethodReturnType.SetValue(dyn, typeof(U).MakeByRefType());

            var il = dyn.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            if (!typeof(T).IsValueType)
                il.Emit(OpCodes.Ldind_Ref);
            il.Emit(OpCodes.Ldflda, field);
            il.Emit(OpCodes.Ret);

            return (Accessor)dyn.CreateDelegate(typeof(Accessor));
        }

19 View Source File : EntityCache.cs
License : Apache License 2.0
Project Creator : aadreja

internal static T CloneObjectWithIL<T>(T enreplacedy)
        {
            Type mainType = typeof(T);

            if (!CachedCloneIL.TryGetValue(mainType, out Delegate cloneIL))
            {
                // Create ILGenerator
                DynamicMethod dymMethod = new DynamicMethod("DoClone", mainType, new Type[] { mainType }, true);
                ConstructorInfo cInfo = mainType.GetConstructor(new Type[] { });

                ILGenerator generator = dymMethod.GetILGenerator();

                LocalBuilder lbf = generator.DeclareLocal(mainType);
                //lbf.SetLocalSymInfo("_temp");

                generator.Emit(OpCodes.Newobj, cInfo); //create new instance of object
                generator.Emit(OpCodes.Stloc_0); //load in memory

                Type type = mainType;
                while (type != null && type != typeof(object))
                {
                    foreach (FieldInfo field in type.GetFields(BindingFlags.Instance
                        | BindingFlags.Public
                        | BindingFlags.NonPublic))
                    {
                        // Load the new object on the eval stack... (currently 1 item on eval stack)
                        generator.Emit(OpCodes.Ldloc_0);
                        // Load initial object (parameter)          (currently 2 items on eval stack)
                        generator.Emit(OpCodes.Ldarg_0);
                        // Replace value by field value             (still currently 2 items on eval stack)
                        generator.Emit(OpCodes.Ldfld, field);
                        // Store the value of the top on the eval stack into the object underneath that value on the value stack.
                        //  (0 items on eval stack)
                        generator.Emit(OpCodes.Stfld, field);
                    }
                    type = type.BaseType;
                }
                

                // Load new constructed obj on eval stack -> 1 item on stack
                generator.Emit(OpCodes.Ldloc_0);
                // Return constructed object.   --> 0 items on stack
                generator.Emit(OpCodes.Ret);

                cloneIL = dymMethod.CreateDelegate(typeof(Func<T, T>));
                CachedCloneIL.Add(mainType, cloneIL);
            }
            return ((Func<T, T>)cloneIL)(enreplacedy);
        }

19 View Source File : ReflectionHandlerFactory.cs
License : MIT License
Project Creator : aquilahkj

private static GetValueHandler CreateFieldGetHandler(FieldInfo field)
        {
            var method = new DynamicMethod("", typeof(object), new[] {typeof(object)}, field.DeclaringType);
            var iLGenerator = method.GetILGenerator();
            iLGenerator.Emit(OpCodes.Ldarg_0);
            iLGenerator.Emit(OpCodes.Ldfld, field);
            EmitBoxIfNeeded(iLGenerator, field.FieldType);
            iLGenerator.Emit(OpCodes.Ret);
            return (GetValueHandler) method.CreateDelegate(typeof(GetValueHandler));
        }

19 View Source File : TypeExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Func<TArg, TRes> CreateFunc<TArg, TRes>(TypeInfo callInfo, string methodName, TypeInfo argInfo, TypeInfo resInfo)
        {
            var typeConstructor = resInfo.GetConstructor(Type.EmptyTypes);
            if (typeConstructor == null)
                throw new ArgumentException($"类型{callInfo.FullName}没有无参构造函数");
            var innerMethod = callInfo.GetMethod(methodName);
            if (innerMethod == null)
                throw new ArgumentException($"类型{callInfo.FullName}没有名称为{methodName}的方法");
            if (innerMethod.ReturnType != resInfo)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}返回值不为{resInfo.FullName}");
            var args = innerMethod.GetParameters();
            if (args.Length != 1)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}参数不是一个");
            if (args[0].ParameterType != argInfo)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}唯一参数不为{argInfo.FullName}");
            //构造匿名方法
            var callMethod = new DynamicMethod(methodName, typeof(TRes), new[] { typeof(TArg) });
            //构造动态IL(方法内部实现)
            var il = callMethod.GetILGenerator();
            il.Emit(OpCodes.Nop);
            //1 参数类型转换
            il.Emit(OpCodes.Ldarg, 0);
            il.Emit(OpCodes.Castclreplaced, argInfo);
            var arg = il.DeclareLocal(argInfo);
            il.Emit(OpCodes.Stloc, arg);
            //2 调用对象构造
            il.Emit(OpCodes.Newobj, typeConstructor);
            var call = il.DeclareLocal(callInfo);
            il.Emit(OpCodes.Stloc, call);
            //3 方法调用
            il.Emit(OpCodes.Ldloc, call);
            il.Emit(OpCodes.Ldloc, arg);
            il.Emit(OpCodes.Callvirt, innerMethod);
            var ret = il.DeclareLocal(innerMethod.ReturnType);
            //4 返回值转换
            il.Emit(OpCodes.Stloc, ret);
            il.Emit(OpCodes.Ldloc, ret);
            il.Emit(OpCodes.Castclreplaced, typeof(TRes).GetTypeInfo());
            var res = il.DeclareLocal(resInfo);
            //5 返回
            il.Emit(OpCodes.Stloc, res);
            il.Emit(OpCodes.Ldloc, res);
            il.Emit(OpCodes.Ret);
            //返回动态委托
            return callMethod.CreateDelegate(typeof(Func<TArg, TRes>)) as Func<TArg, TRes>;
        }

19 View Source File : TypeExtend.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Func<TRes> CreateFunc<TRes>(TypeInfo callInfo, string methodName, TypeInfo resInfo)
        {
            var typeConstructor = resInfo.GetConstructor(Type.EmptyTypes);
            if (typeConstructor == null)
                throw new ArgumentException($"类型{callInfo.FullName}没有无参构造函数");
            var innerMethod = callInfo.GetMethod(methodName);
            if (innerMethod == null)
                throw new ArgumentException($"类型{callInfo.FullName}没有名称为{methodName}的方法");
            if (innerMethod.ReturnType != resInfo)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}返回值不为{resInfo.FullName}");
            var args = innerMethod.GetParameters();
            if (args.Length > 0)
                throw new ArgumentException($"类型{callInfo.FullName}的方法{methodName}参数不为空");
            //构造匿名方法
            var callMethod = new DynamicMethod(methodName, typeof(TRes), null);
            //构造动态IL(方法内部实现)
            var il = callMethod.GetILGenerator();
            il.Emit(OpCodes.Nop);
            //1 调用对象构造
            il.Emit(OpCodes.Newobj, typeConstructor);
            var call = il.DeclareLocal(callInfo);
            il.Emit(OpCodes.Stloc, call);
            //3 方法调用
            il.Emit(OpCodes.Ldloc, call);
            il.Emit(OpCodes.Callvirt, innerMethod);
            var ret = il.DeclareLocal(innerMethod.ReturnType);
            //4 返回值转换
            il.Emit(OpCodes.Stloc, ret);
            il.Emit(OpCodes.Ldloc, ret);
            il.Emit(OpCodes.Castclreplaced, typeof(TRes).GetTypeInfo());
            var res = il.DeclareLocal(resInfo);
            //5 返回
            il.Emit(OpCodes.Stloc, res);
            il.Emit(OpCodes.Ldloc, res);
            il.Emit(OpCodes.Ret);
            //返回动态委托
            return callMethod.CreateDelegate(typeof(Func<TRes>)) as Func<TRes>;
        }

19 View Source File : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

internal static Func<IDataReader, T> ReaderToObject(IDataReader rdr)
        {
            MethodInfo rdrGetValueMethod = rdr.GetType().GetMethod("get_Item", new Type[] { typeof(int) });

            Type[] args = { typeof(IDataReader) };
            DynamicMethod method = new DynamicMethod("DynamicRead" + Guid.NewGuid().ToString(), typeof(T), args, typeof(Repository<T>).Module, true);
            ILGenerator il = method.GetILGenerator();

            LocalBuilder result = il.DeclareLocal(typeof(T)); //loc_0
            il.Emit(OpCodes.Newobj, typeof(T).GetConstructor(Type.EmptyTypes));
            il.Emit(OpCodes.Stloc_0, result); //Pops the current value from the top of the evaluation stack and stores it in a the local variable list at a specified index.

            Label tryBlock = il.BeginExceptionBlock();

            LocalBuilder valueCopy = il.DeclareLocal(typeof(object)); //declare local variable to store object value. loc_1

            il.DeclareLocal(typeof(int)); //declare local variable to store index //loc_2
            il.Emit(OpCodes.Ldc_I4_0); //load 0 in index
            il.Emit(OpCodes.Stloc_2); //pop and save to local variable loc 2

            //get FieldInfo of all properties
            TableAttribute tableInfo = EnreplacedyCache.Get(typeof(T));

            for (int i = 0; i < rdr.FieldCount; i++)
            {
                tableInfo.Columns.TryGetValue(rdr.GetName(i), out ColumnAttribute columnInfo);

                if (columnInfo != null && columnInfo.SetMethod != null)
                {
                    Label endIfLabel = il.DefineLabel();

                    il.Emit(OpCodes.Ldarg_0);//load the argument. Loads the argument at index 0 onto the evaluation stack.
                    il.Emit(OpCodes.Ldc_I4, i); //push field index as int32 to the stack. Pushes a supplied value of type int32 onto the evaluation stack as an int32.
                    il.Emit(OpCodes.Dup);//copy value
                    il.Emit(OpCodes.Stloc_2);//pop and save value to loc 2
                    il.Emit(OpCodes.Callvirt, rdrGetValueMethod); //Call rdr[i] method - Calls a late - bound method on an object, pushing the return value onto the evaluation stack.

                    //TODO: dynamic location using valueCopyLocal
                    il.Emit(OpCodes.Stloc_1); //pop the value and push in stack location 1
                    il.Emit(OpCodes.Ldloc_1); //load the variable in location 1

                    il.Emit(OpCodes.Isinst, typeof(DBNull)); //check whether value is null - Tests whether an object reference (type O) is an instance of a particular clreplaced.
                    il.Emit(OpCodes.Brtrue, endIfLabel); //go to end block if value is null

                    il.Emit(OpCodes.Ldloc_0); //load T result
                    il.Emit(OpCodes.Ldloc_1); //TODO: dynamic location using valueCopyLocal

                    //when Enum are without number values
                    if (columnInfo.Property.PropertyType.IsEnum)
                    {
                        Type numericType = Enum.GetUnderlyingType(columnInfo.Property.PropertyType);
                        if (rdr.GetFieldType(i) == typeof(string))
                        {
                            LocalBuilder stringEnumLocal = il.DeclareLocal(typeof(string));

                            il.Emit(OpCodes.Castclreplaced, typeof(string)); // stack is now [...][string]
                            il.Emit(OpCodes.Stloc, stringEnumLocal); // stack is now [...]
                            il.Emit(OpCodes.Ldtoken, columnInfo.Property.PropertyType); // stack is now [...][enum-type-token]
                            il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null);// stack is now [...][enum-type]
                            il.Emit(OpCodes.Ldloc, stringEnumLocal); // stack is now [...][enum-type][string]
                            il.Emit(OpCodes.Ldc_I4_1); // stack is now [...][enum-type][string][true]
                            il.EmitCall(OpCodes.Call, enumParse, null); // stack is now [...][enum-as-object]
                            il.Emit(OpCodes.Unbox_Any, columnInfo.Property.PropertyType); // stack is now [...][typed-value]
                        }
                        else
                        {
                            ConvertValueToEnum(il, rdr.GetFieldType(i), columnInfo.Property.PropertyType, numericType);
                        }
                    }
                    else if (columnInfo.Property.PropertyType.IsValueType)
                        il.Emit(OpCodes.Unbox_Any, rdr.GetFieldType(i)); //type cast

                    // for nullable type fields
                    if (columnInfo.Property.PropertyType.IsGenericType && columnInfo.Property.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        var underlyingType = Nullable.GetUnderlyingType(columnInfo.Property.PropertyType);
                        il.Emit(OpCodes.Newobj, columnInfo.Property.PropertyType.GetConstructor(new Type[] { underlyingType }));
                    }

                    il.Emit(OpCodes.Callvirt, columnInfo.SetMethod);
                    il.Emit(OpCodes.Nop);

                    il.MarkLabel(endIfLabel);
                }
            }

            il.BeginCatchBlock(typeof(Exception)); //begin try block. exception is in stack
            il.Emit(OpCodes.Ldloc_2); //load index
            il.Emit(OpCodes.Ldarg_0); //load argument reader
            il.Emit(OpCodes.Ldloc_1); //load value //TODO: dynamic location using valueCopyLocal
            il.EmitCall(OpCodes.Call, typeof(ReaderCache<T>).GetMethod(nameof(ReaderCache<T>.HandleException)), null); //call exception handler
            il.EndExceptionBlock();

            il.Emit(OpCodes.Ldloc, result);
            il.Emit(OpCodes.Ret);
            

            var funcType = System.Linq.Expressions.Expression.GetFuncType(typeof(IDataReader), typeof(T));
            return (Func<IDataReader, T>)method.CreateDelegate(funcType);
        }

19 View Source File : ZeroDiscover.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public static Func<TRes> CreateFunc<TRes>(TypeInfo callInfo, string methodName, TypeInfo resInfo)
        {
            ConstructorInfo constructor = callInfo.GetConstructor(Type.EmptyTypes);
            if (constructor == (ConstructorInfo)null)
                throw new ArgumentException("类型" + callInfo.FullName + "没有无参构造函数");
            MethodInfo method = callInfo.GetMethod(methodName);
            if (method == (MethodInfo)null)
                throw new ArgumentException("类型" + callInfo.FullName + "没有名称为" + methodName + "的方法");
            if (method.ReturnType != (Type)resInfo)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "返回值不为" + resInfo.FullName);
            if ((uint)method.GetParameters().Length > 0U)
                throw new ArgumentException("类型" + callInfo.FullName + "的方法" + methodName + "参数不为空");
            DynamicMethod dynamicMethod = new DynamicMethod(methodName, typeof(TRes), (Type[])null);
            ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
            ilGenerator.Emit(OpCodes.Nop);
            ilGenerator.Emit(OpCodes.Newobj, constructor);
            LocalBuilder local1 = ilGenerator.DeclareLocal((Type)callInfo);
            ilGenerator.Emit(OpCodes.Stloc, local1);
            ilGenerator.Emit(OpCodes.Ldloc, local1);
            ilGenerator.Emit(OpCodes.Callvirt, method);
            LocalBuilder local2 = ilGenerator.DeclareLocal(method.ReturnType);
            ilGenerator.Emit(OpCodes.Stloc, local2);
            ilGenerator.Emit(OpCodes.Ldloc, local2);
            ilGenerator.Emit(OpCodes.Castclreplaced, (Type)typeof(TRes).GetTypeInfo());
            LocalBuilder local3 = ilGenerator.DeclareLocal((Type)resInfo);
            ilGenerator.Emit(OpCodes.Stloc, local3);
            ilGenerator.Emit(OpCodes.Ldloc, local3);
            ilGenerator.Emit(OpCodes.Ret);
            return dynamicMethod.CreateDelegate(typeof(Func<TRes>)) as Func<TRes>;
        }

19 View Source File : DirectCall.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public static MethodBase GetDirectInvocationProxy(MethodBase method)
        {
            var proxy = (MethodBase) directProxies[method];
            if(proxy != null)
                return proxy;

            lock(directProxies)
            {
                proxy = (MethodBase) directProxies[method];
                if(proxy != null)
                    return proxy;

                var parameters = method.GetParameters();
                var paramTypes = new Type[parameters.Length + (method.IsStatic ? 0 : 1)];
                for(var i = 0; i < paramTypes.Length; i++)
                    if(method.IsStatic)
                    {
                        paramTypes[i] = parameters[i].ParameterType;
                    }
                    else
                    {
                        if(i == 0)
                            paramTypes[0] = method.DeclaringType;
                        else
                            paramTypes[i] = parameters[i - 1].ParameterType;
                    }

                var retType = method is MethodInfo ? ((MethodInfo) method).ReturnType : typeof(void);
                var dm = new DynamicMethod("", retType, paramTypes, Unverifier.Module, true);
                var gen = dm.GetILGenerator();
                for(var i = 0; i < paramTypes.Length; i++)
                    if(!method.IsStatic && i == 0 && paramTypes[0].IsValueType)
                        gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, i);
                    else
                        gen.Emit(System.Reflection.Emit.OpCodes.Ldarg, i);
                if(method is MethodInfo)
                    gen.Emit(System.Reflection.Emit.OpCodes.Call, (MethodInfo) method);
                else
                    gen.Emit(System.Reflection.Emit.OpCodes.Call, (ConstructorInfo) method);
                gen.Emit(System.Reflection.Emit.OpCodes.Ret);

                directProxies[method] = dm;
                return dm;
            }
        }

19 View Source File : DynamicReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
        {
            DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType);
            ILGenerator generator = dynamicMethod.GetILGenerator();

            GenerateCreateMethodCallIL(method, generator, 1);

            return (MethodCall<T, object>)dynamicMethod.CreateDelegate(typeof(MethodCall<T, object>));
        }

19 View Source File : DynamicReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
        {
            if (fieldInfo.IsLiteral)
            {
                object constantValue = fieldInfo.GetValue(null);
                Func<T, object> getter = o => constantValue;
                return getter;
            }

            DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + fieldInfo.Name, typeof(T), new[] { typeof(object) }, fieldInfo.DeclaringType);
            ILGenerator generator = dynamicMethod.GetILGenerator();

            GenerateCreateGetFieldIL(fieldInfo, generator);

            return (Func<T, object>)dynamicMethod.CreateDelegate(typeof(Func<T, object>));
        }

19 View Source File : SizeOfHelper.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static int GetSize(Type type)
        {
            var dm = new DynamicMethod("", typeof(int), Type.EmptyTypes, Unverifier.Module, true);
            var gen = dm.GetILGenerator();

            gen.Emit(System.Reflection.Emit.OpCodes.Sizeof, type);
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

            return (int) dm.Invoke(null, null);
        }

19 View Source File : DynamicReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
        {
            DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType);
            ILGenerator generator = dynamicMethod.GetILGenerator();

            GenerateCreateSetFieldIL(fieldInfo, generator);

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

19 View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja

internal static Action<object, object> CreateSetProperty(Type enreplacedyType, string propertyName)
        {
            MethodInfo mi = enreplacedyType.GetProperty(propertyName).SetMethod;

            if (mi == null) return null; //no set property

            Type[] args = new Type[] { typeof(object), typeof(object) };

            DynamicMethod method = new DynamicMethod("Set_" + enreplacedyType.Name + "_" + propertyName, null, args, enreplacedyType.Module, true);
            ILGenerator setIL = method.GetILGenerator();

            Type paramType = mi.GetParameters()[0].ParameterType;

            //setIL.DeclareLocal(typeof(object));
            setIL.Emit(OpCodes.Ldarg_0); //Load the first argument [Enreplacedy]
                                            //(target object)
                                            //Cast to the source type
            setIL.Emit(OpCodes.Castclreplaced, enreplacedyType);
            setIL.Emit(OpCodes.Ldarg_1); //Load the second argument [Value]
                                            //(value object)
            if (paramType.IsValueType)
            {
                setIL.Emit(OpCodes.Unbox, paramType); //Unbox it 
                if (mTypeHash[paramType] != null) //and load
                {
                    OpCode load = (OpCode)mTypeHash[paramType];
                    setIL.Emit(load);
                }
                else
                {
                    setIL.Emit(OpCodes.Ldobj, paramType);
                }
            }
            else
            {
                setIL.Emit(OpCodes.Castclreplaced, paramType); //Cast clreplaced
            }

            setIL.EmitCall(OpCodes.Callvirt, mi, null); //Set the property value
            setIL.Emit(OpCodes.Ret);

            var actionType = System.Linq.Expressions.Expression.GetActionType(typeof(object), typeof(object));
            return (Action<object, object>)method.CreateDelegate(actionType);
        }

19 View Source File : Util.cs
License : MIT License
Project Creator : albahari

public static Func<object, object> GenDynamicField (FieldInfo fld)
		{
			DynamicMethod dynMeth;
			if (fld.DeclaringType.IsInterface)
				dynMeth = new DynamicMethod ("", typeof (object), new[] { typeof (object) });
			else
				dynMeth = new DynamicMethod ("", typeof (object), new[] { typeof (object) }, fld.DeclaringType);
			ILGenerator gen = dynMeth.GetILGenerator ();
			gen.Emit (OpCodes.Ldarg_0);

			if (fld.DeclaringType.IsValueType)
			{
				gen.DeclareLocal (fld.DeclaringType);
				gen.Emit (OpCodes.Unbox_Any, fld.DeclaringType);
				gen.Emit (OpCodes.Stloc_0);
				gen.Emit (OpCodes.Ldloca_S, 0);
			}
			else
				gen.Emit (OpCodes.Castclreplaced, fld.DeclaringType);

			gen.Emit (OpCodes.Ldfld, fld);
			if (fld.FieldType.IsValueType) gen.Emit (OpCodes.Box, fld.FieldType);
			gen.Emit (OpCodes.Ret);
			return (Func<object, object>)dynMeth.CreateDelegate (typeof (Func<object, object>));
		}

19 View Source File : DarksVMTrampoline.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static DynamicMethod CreateTrampolineTyped(int moduleId, ulong codeAdr, uint key, DarksVMFuncSig sig, uint sigId)
        {
            var dm = new DynamicMethod("", sig.RetType, sig.ParamTypes, Unverifier.Module, true);

            var gen = dm.GetILGenerator();
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, moduleId);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I8, (long) codeAdr);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int) key);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, (int) sigId);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, sig.ParamTypes.Length);
            gen.Emit(System.Reflection.Emit.OpCodes.Newarr, typeof(void*));
            for(var i = 0; i < sig.ParamTypes.Length; i++)
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Dup);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldc_I4, i);
                if(sig.ParamTypes[i].IsByRef)
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarg, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, sig.ParamTypes[i].GetElementType());
                }
                else
                {
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, i);
                    gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, sig.ParamTypes[i]);
                }
                var local = gen.DeclareLocal(typeof(TypedReference));
                gen.Emit(System.Reflection.Emit.OpCodes.Stloc, local);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, local);
                gen.Emit(System.Reflection.Emit.OpCodes.Conv_I);
                gen.Emit(System.Reflection.Emit.OpCodes.Stelem_I);
            }

            if(sig.RetType != typeof(void))
            {
                var retVar = gen.DeclareLocal(sig.RetType);
                var retRef = gen.DeclareLocal(typeof(TypedReference));
                gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, retVar);
                gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, sig.RetType);
                gen.Emit(System.Reflection.Emit.OpCodes.Stloc, retRef);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldloca, retRef);
                gen.Emit(System.Reflection.Emit.OpCodes.Call, entryStubTyped);

                gen.Emit(System.Reflection.Emit.OpCodes.Ldloc, retVar);
            }
            else
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Ldnull);
                gen.Emit(System.Reflection.Emit.OpCodes.Call, entryStubTyped);
            }
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

            return dm;
        }

19 View Source File : ReflectionUtils.cs
License : MIT License
Project Creator : alelievr

public static Delegate CreateGenericGetterDelegate(Type childType, FieldInfo field)
		{
			//Create the delegate type that takes our node type in parameter
			var delegateType = typeof(ChildFieldGetter<>).MakeGenericType(new Type[] { childType });

			//Get the child field from base clreplaced
			FieldInfo fi = childType.GetField(field.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.Instance);

			#if NET_4_6
				ParameterExpression targetExp = Expression.Parameter(childType, "target");

				// Expression.Property can be used here as well
				MemberExpression fieldExp = Expression.Field(targetExp, fi);

				var l = Expression.Lambda(delegateType, fieldExp, targetExp).Compile();
				Debug.Log("here: " + l);
				return l;
			#else
	
				//Create a new method which return the field fi
				DynamicMethod dm = new DynamicMethod("Get" + fi.Name, typeof(object), new Type[] { childType }, childType);
				ILGenerator il = dm.GetILGenerator();
				// Load the instance of the object (argument 0) onto the stack
				il.Emit(OpCodes.Ldarg_0);
				// Load the value of the object's field (fi) onto the stack
				il.Emit(OpCodes.Ldfld, fi);
				// return the value on the top of the stack
				il.Emit(OpCodes.Ret);
	
				return dm.CreateDelegate(delegateType);
			#endif
		}

19 View Source File : Redirection.Reactive.cs
License : MIT License
Project Creator : 71

private static MethodRedirection CreateDynamicRedirection(MethodBase method, out int id)
        {
            // Make id
            do
            {
                id = ObservingRedirectionsIdGenerator.Next();
            }
            while (ObservingRedirections.ContainsKey(id));

            // Creates an array containing all parameter types
            int diff = method.IsStatic ? 0 : 1;

            ParameterInfo[] originalParameters = method.GetParameters();
            Type[] originalParameterTypes = new Type[originalParameters.Length + diff];

            if (diff == 1 /* !method.IsStatic */)
                originalParameterTypes[0] = method.DeclaringType;

            for (int i = 0; i < originalParameters.Length; i++)
            {
                originalParameterTypes[i + diff] = originalParameters[i].ParameterType;
            }

            // Create an identical method
            bool isCtor = method is ConstructorInfo;
            Type returnType = isCtor ? typeof(void) : ((MethodInfo)method).ReturnType;

            DynamicMethod dyn = new DynamicMethod(
                name:              method.Name,
                attributes:        MethodAttributes.Public | MethodAttributes.Static,
                callingConvention: CallingConventions.Standard,
                returnType:        returnType,
                parameterTypes:    originalParameterTypes,
                owner:             method.DeclaringType,
                skipVisibility:    true);

            // Make the method call the observable
            ILGenerator il = dyn.GetILGenerator();
            {
                // This is in a block to make every more readable,
                // the following comments describe what's happening in the generated method.

                // Emit "this", or "null"
                if (method.IsStatic)
                {
                    il.Emit(OpCodes.Ldnull);
                }
                else
                {
                    il.Emit(OpCodes.Ldarg_0);

                    if (method.DeclaringType.GetTypeInfo().IsValueType)
                    {
                        il.Emit(OpCodes.Ldobj, method.DeclaringType);
                        il.Emit(OpCodes.Box, method.DeclaringType);
                    }
                }

                // Create an array containing all parameters
                il.Emit(OpCodes.Ldc_I4, originalParameters.Length);
                il.Emit(OpCodes.Newarr, typeof(object));

                for (int i = 0; i < originalParameters.Length; i++)
                {
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldc_I4, i);
                    il.Emit(OpCodes.Ldarg, i + diff);

                    Type parameterType = originalParameterTypes[i + diff];

                    if (parameterType.GetTypeInfo().IsValueType)
                        il.Emit(OpCodes.Box, parameterType);

                    il.Emit(OpCodes.Stelem_Ref);
                }

                // Array is still on stack (thanks to dup)
                // Emit id
                il.Emit(OpCodes.Ldc_I4, id);

                // Call "hook" method
                il.Emit(OpCodes.Call, typeof(Redirection).GetMethod(nameof(OnInvoked), BindingFlags.Static | BindingFlags.NonPublic));

                // Return returned result
                // (But first, cast it if needed)
                if (returnType == typeof(void))
                    il.Emit(OpCodes.Pop);
                else if (returnType.GetTypeInfo().IsValueType)
                    il.Emit(OpCodes.Unbox_Any, returnType);
                else if (returnType != typeof(object))
                    il.Emit(OpCodes.Castclreplaced, returnType);

                il.Emit(OpCodes.Ret);
            }

            // Return the redirection
            return new MethodRedirection(method, dyn, false);
        }

19 View Source File : EmitMemberAccessor.cs
License : MIT License
Project Creator : AllocZero

public static Func<object>? CreateConstructor(Type type)
        {
            Debug.replacedert(type != null);
            ConstructorInfo? realMethod = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, binder: null, Type.EmptyTypes, modifiers: null);

            if (type.IsAbstract)
            {
                return null;
            }

            if (realMethod == null && !type.IsValueType)
            {
                return null;
            }

            var dynamicMethod = new DynamicMethod(
                ConstructorInfo.ConstructorName,
                ObjectType,
                Type.EmptyTypes,
                typeof(EmitMemberAccessor).Module,
                skipVisibility: true);

            ILGenerator generator = dynamicMethod.GetILGenerator();

            if (realMethod == null)
            {
                LocalBuilder local = generator.DeclareLocal(type);

                generator.Emit(OpCodes.Ldloca_S, local);
                generator.Emit(OpCodes.Initobj, type);
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Box, type);
            }
            else
            {
                generator.Emit(OpCodes.Newobj, realMethod);
            }

            generator.Emit(OpCodes.Ret);

            return (Func<object>?)dynamicMethod.CreateDelegate(typeof(Func<object>));
        }

19 View Source File : EHHelper.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static bool BuildInternalPreserve(Type type)
        {
            try
            {
                const BindingFlags fl = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod;
                var at = (string) typeof(Environment).InvokeMember("GetResourceString", fl, null, null, new object[] {"Word_At"});

                var preserve = type.GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
                var field = type.GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic);
                var stackTrace = type.GetProperty("StackTrace", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
                var fmt = typeof(string).GetMethod("Format", new[] {typeof(string), typeof(object), typeof(object)});

                var dm = new DynamicMethod("", typeof(void), new[] {typeof(Exception), typeof(string), typeof(bool)}, true);
                var ilGen = dm.GetILGenerator();
                var lbl = ilGen.DefineLabel();
                var lbl2 = ilGen.DefineLabel();
                var lbl3 = ilGen.DefineLabel();

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Callvirt, stackTrace);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Br, lbl3);
                ilGen.MarkLabel(lbl2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.MarkLabel(lbl3);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, preserve);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brfalse, lbl);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Brtrue, lbl);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);

                ilGen.Emit(System.Reflection.Emit.OpCodes.Dup);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldstr,
                    "{1}" + Environment.NewLine + "   " + at + " DarksVM.Load() [{0}]" + Environment.NewLine);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, fmt);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Stfld, field);


                ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);

                ilGen.MarkLabel(lbl);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Throw);

                rethrow = (Throw) dm.CreateDelegate(typeof(Throw));
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex);
                return false;
            }
            return true;
        }

19 View Source File : EmitMemberAccessor.cs
License : MIT License
Project Creator : AllocZero

private static DynamicMethod CreatePropertySetter(PropertyInfo propertyInfo, Type runtimePropertyType)
        {
            MethodInfo? realMethod = propertyInfo.SetMethod;
            Debug.replacedert(realMethod != null);

            Type? declaringType = propertyInfo.DeclaringType;
            Debug.replacedert(declaringType != null);

            Type declaredPropertyType = propertyInfo.PropertyType;

            DynamicMethod dynamicMethod = CreateSetterMethod(propertyInfo.Name, runtimePropertyType);
            ILGenerator generator = dynamicMethod.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(declaringType.IsValueType ? OpCodes.Unbox : OpCodes.Castclreplaced, declaringType);
            generator.Emit(OpCodes.Ldarg_1);

            // declaredPropertyType: Type of the property
            // runtimePropertyType:  <T> of JsonConverter / JsonPropertyInfo

            if (declaredPropertyType != runtimePropertyType && declaredPropertyType.IsValueType)
            {
                generator.Emit(OpCodes.Unbox_Any, declaredPropertyType);
            }

            generator.Emit(declaringType.IsValueType ? OpCodes.Call : OpCodes.Callvirt, realMethod);
            generator.Emit(OpCodes.Ret);

            return dynamicMethod;
        }

19 View Source File : PrefixWriter.cs
License : MIT License
Project Creator : Abc-Arbitrage

private static Action<PrefixWriter, ILogEventHeader> BuildAppendMethod(ICollection<PatternPart> parts, Dictionary<string, (int offset, int length)> stringMap)
        {
            var method = new DynamicMethod("WritePrefix", typeof(void), new[] { typeof(PrefixWriter), typeof(ILogEventHeader) }, typeof(PrefixWriter), false)
            {
                InitLocals = false
            };

            var il = method.GetILGenerator();

            var stringBufferLocal = il.DeclareLocal(typeof(StringBuffer));
            var stringsLocal = il.DeclareLocal(typeof(char).MakeByRefType(), true);
            var dateTimeLocal = default(LocalBuilder);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_stringBuffer), BindingFlags.Instance | BindingFlags.NonPublic)!);
            il.Emit(OpCodes.Stloc, stringBufferLocal);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, typeof(PrefixWriter).GetField(nameof(_strings), BindingFlags.Instance | BindingFlags.NonPublic)!);
            il.Emit(OpCodes.Ldc_I4_0);
            il.Emit(OpCodes.Ldelema, typeof(char));
            il.Emit(OpCodes.Stloc, stringsLocal);

            foreach (var part in parts)
            {
                switch (part.Type)
                {
                    case PatternPartType.String:
                    {
                        // _stringBuffer.Append(&_strings[0] + offset * sizeof(char), length);

                        var (offset, length) = stringMap[part.Value!];

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldloc, stringsLocal);
                        il.Emit(OpCodes.Conv_U);
                        il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
                        il.Emit(OpCodes.Add);

                        il.Emit(OpCodes.Ldc_I4, length);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(char*), typeof(int) })!);
                        break;
                    }

                    case PatternPartType.Date:
                    {
                        // _stringBuffer.Append(logEventHeader.Timestamp, new StringView(&_strings[0] + offset * sizeof(char), length));

                        var (offset, length) = stringMap[_dateFormat];

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);

                        il.Emit(OpCodes.Ldloc, stringsLocal);
                        il.Emit(OpCodes.Conv_U);
                        il.Emit(OpCodes.Ldc_I4, offset * sizeof(char));
                        il.Emit(OpCodes.Add);

                        il.Emit(OpCodes.Ldc_I4, length);

                        il.Emit(OpCodes.Newobj, typeof(StringView).GetConstructor(new[] { typeof(char*), typeof(int) })!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(DateTime), typeof(StringView) })!);
                        break;
                    }

                    case PatternPartType.Time:
                    {
                        // _stringBuffer.Append(logEventHeader.Timestamp.TimeOfDay, StringView.Empty);

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Timestamp))?.GetGetMethod()!);
                        il.Emit(OpCodes.Stloc, dateTimeLocal ??= il.DeclareLocal(typeof(DateTime)));
                        il.Emit(OpCodes.Ldloca, dateTimeLocal);
                        il.Emit(OpCodes.Call, typeof(DateTime).GetProperty(nameof(DateTime.TimeOfDay))?.GetGetMethod()!);

                        il.Emit(OpCodes.Ldsfld, typeof(StringView).GetField(nameof(StringView.Empty))!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(TimeSpan), typeof(StringView) })!);
                        break;
                    }

                    case PatternPartType.Thread:
                    {
                        // AppendThread(logEventHeader.Thread);

                        il.Emit(OpCodes.Ldarg_0);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Thread))?.GetGetMethod()!);

                        il.Emit(OpCodes.Call, typeof(PrefixWriter).GetMethod(nameof(AppendThread), BindingFlags.Instance | BindingFlags.NonPublic)!);
                        break;
                    }

                    case PatternPartType.Level:
                    {
                        // _stringBuffer.Append(LevelStringCache.GetLevelString(logEventHeader.Level));

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Level))?.GetGetMethod()!);
                        il.Emit(OpCodes.Call, typeof(LevelStringCache).GetMethod(nameof(LevelStringCache.GetLevelString))!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
                        break;
                    }

                    case PatternPartType.Logger:
                    {
                        // _stringBuffer.Append(logEventHeader.Name);

                        il.Emit(OpCodes.Ldloc, stringBufferLocal);

                        il.Emit(OpCodes.Ldarg_1);
                        il.Emit(OpCodes.Callvirt, typeof(ILogEventHeader).GetProperty(nameof(ILogEventHeader.Name))?.GetGetMethod()!);

                        il.Emit(OpCodes.Call, typeof(StringBuffer).GetMethod(nameof(StringBuffer.Append), new[] { typeof(string) })!);
                        break;
                    }

                    default:
                        throw new ArgumentOutOfRangeException();
                }
            }

            il.Emit(OpCodes.Ret);

            return (Action<PrefixWriter, ILogEventHeader>)method.CreateDelegate(typeof(Action<PrefixWriter, ILogEventHeader>));
        }

19 View Source File : MSILGenerator.cs
License : MIT License
Project Creator : aloneguid

public replacedignArrayDelegate Generatereplacedigner(DataColumn dataColumn, Type clreplacedType)
      {
         DataField fileField = dataColumn.Field;
         Schema typeSchema = SchemaReflector.Reflect(clreplacedType);
         DataField typeField = typeSchema.FindDataField(fileField.Path);

         Type[] methodArgs = { typeof(DataColumn), typeof(Array) };
         var runMethod = new DynamicMethod(
            $"Set{clreplacedType.Name}{typeField.ClrPropName}",
            typeof(void),
            methodArgs,
            GetType().GetTypeInfo().Module);

         ILGenerator il = runMethod.GetILGenerator();

         //set clreplaced property method
         TypeInfo ti = clreplacedType.GetTypeInfo();
         PropertyInfo pi = ti.GetDeclaredProperty(typeField.ClrPropName ?? typeField.Name);
         MethodInfo setValueMethod = pi.SetMethod;

         TypeInfo dcti = dataColumn.GetType().GetTypeInfo();
         MethodInfo getDataMethod = dcti.GetDeclaredProperty(nameof(DataColumn.Data)).GetMethod;
         MethodInfo getRepsMethod = dcti.GetDeclaredProperty(nameof(DataColumn.RepereplacedionLevels)).GetMethod;

         TypeConversion conversion = GetConversion(dataColumn.Field.ClrNullableIfHasNullsType, pi.PropertyType);

         Generatereplacedigner(il, clreplacedType, typeField,
            setValueMethod,
            getDataMethod,
            getRepsMethod,
            conversion);

         return (replacedignArrayDelegate)runMethod.CreateDelegate(typeof(replacedignArrayDelegate));
      }

19 View Source File : TypedReferenceHelpers.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static Unbox BuildUnboxHelper(Type boxType)
        {
            var dm = new DynamicMethod("", typeof(void), new[] {typeof(object), typeof(TypedRefPtr)}, Unverifier.Module, true);
            var gen = dm.GetILGenerator();

            gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, 1);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldfld, typedPtrField);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            gen.Emit(System.Reflection.Emit.OpCodes.Unbox, boxType); // Unbox pointer is readonly? Never mind...
            gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, boxType);
            gen.Emit(System.Reflection.Emit.OpCodes.Stobj, typeof(TypedReference));
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

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

19 View Source File : Accessor.cs
License : MIT License
Project Creator : andruzzzhka

private static (Getter, Setter) MakeAccessors(string propName)
        {
            var prop = typeof(T).GetProperty(propName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            if (prop == null)
                throw new MissingMemberException(typeof(T).Name, propName);

            var getM = prop.GetGetMethod(true);
            var setM = prop.GetSetMethod(true);
            Getter getter = null;
            Setter setter = null;

            if (typeof(T).IsValueType)
            {
                if (getM != null)
                    getter = (Getter)Delegate.CreateDelegate(typeof(Getter), getM);
                if (setM != null)
                    setter = (Setter)Delegate.CreateDelegate(typeof(Setter), setM);
            }
            else
            {
                if (getM != null)
                {
                    var dyn = new DynamicMethod($"<>_get__{propName}", typeof(U), new[] { typeof(T).MakeByRefType() }, typeof(PropertyAccessor<T, U>), true);
                    var il = dyn.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldind_Ref);
                    il.Emit(OpCodes.Tailcall);
                    il.Emit(getM.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, getM);
                    il.Emit(OpCodes.Ret);
                    getter = (Getter)dyn.CreateDelegate(typeof(Getter));
                }
                if (setM != null)
                {
                    var dyn = new DynamicMethod($"<>_set__{propName}", typeof(void), new[] { typeof(T).MakeByRefType(), typeof(U) }, typeof(PropertyAccessor<T, U>), true);
                    var il = dyn.GetILGenerator();
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldind_Ref);
                    il.Emit(OpCodes.Ldarg_1);
                    il.Emit(OpCodes.Tailcall);
                    il.Emit(setM.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, setM);
                    il.Emit(OpCodes.Ret);
                    setter = (Setter)dyn.CreateDelegate(typeof(Setter));
                }
            }

            return (getter, setter);
        }

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private Func<IDataRecord, T> CreateTypeSerializerHandler<T>(MemberMapper mapper, IDataRecord record)
        {
            var type = typeof(T);
            var methodName = $"Serializer{Guid.NewGuid():N}";
            var dynamicMethod = new DynamicMethod(methodName, type, new Type[] { typeof(IDataRecord) }, type, true);
            var generator = dynamicMethod.GetILGenerator();
            LocalBuilder local = generator.DeclareLocal(type);
            var dataInfos = new DataReaderCellInfo[record.FieldCount];
            for (int i = 0; i < record.FieldCount; i++)
            {
                var dataname = record.GetName(i);
                var datatype = record.GetFieldType(i);
                var typename = record.GetDataTypeName(i);
                dataInfos[i] = new DataReaderCellInfo(i, typename, datatype, dataname);
            }
            if (dataInfos.Length == 1 && (type.IsValueType || type == typeof(string) || type == typeof(object)))
            {
                var dataInfo = dataInfos.First();
                var convertMethod = mapper.FindConvertMethod(type, dataInfo.DataType);
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldc_I4, 0);
                if (convertMethod.IsVirtual)
                    generator.Emit(OpCodes.Callvirt, convertMethod);
                else
                    generator.Emit(OpCodes.Call, convertMethod);
                if (type == typeof(object) && convertMethod.ReturnType.IsValueType)
                {
                    generator.Emit(OpCodes.Box, convertMethod.ReturnType);
                }
                generator.Emit(OpCodes.Stloc, local);
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
            var constructor = mapper.FindConstructor(type);
            if (constructor.GetParameters().Length > 0)
            {
                var parameters = constructor.GetParameters();
                var locals = new LocalBuilder[parameters.Length];
                for (int i = 0; i < locals.Length; i++)
                {
                    locals[i] = generator.DeclareLocal(parameters[i].ParameterType);
                }
                for (int i = 0; i < locals.Length; i++)
                {
                    var item = mapper.FindConstructorParameter(dataInfos, parameters[i]);
                    if (item == null)
                    {
                        continue;
                    }
                    var convertMethod = mapper.FindConvertMethod(parameters[i].ParameterType, item.DataType);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.Emit(OpCodes.Ldc_I4, item.Ordinal);
                    if (convertMethod.IsVirtual)
                        generator.Emit(OpCodes.Callvirt, convertMethod);
                    else
                        generator.Emit(OpCodes.Call, convertMethod);
                    generator.Emit(OpCodes.Stloc, locals[i]);
                }
                for (int i = 0; i < locals.Length; i++)
                {
                    generator.Emit(OpCodes.Ldloc, locals[i]);
                }
                generator.Emit(OpCodes.Newobj, constructor);
                generator.Emit(OpCodes.Stloc, local);
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
            else
            {
                var properties = type.GetProperties();
                generator.Emit(OpCodes.Newobj, constructor);
                generator.Emit(OpCodes.Stloc, local);
                foreach (var item in dataInfos)
                {
                    var property = mapper.FindMember(properties, item) as PropertyInfo;
                    if (property == null)
                    {
                        continue;
                    }
                    var convertMethod = mapper.FindConvertMethod(property.PropertyType, item.DataType);
                    if (convertMethod == null)
                    {
                        continue;
                    }
                    int i = record.GetOrdinal(item.DataName);
                    generator.Emit(OpCodes.Ldloc, local);
                    generator.Emit(OpCodes.Ldarg_0);
                    generator.Emit(OpCodes.Ldc_I4, i);
                    if (convertMethod.IsVirtual)
                        generator.Emit(OpCodes.Callvirt, convertMethod);
                    else
                        generator.Emit(OpCodes.Call, convertMethod);
                    generator.Emit(OpCodes.Callvirt, property.GetSetMethod());
                }
                generator.Emit(OpCodes.Ldloc, local);
                generator.Emit(OpCodes.Ret);
                return dynamicMethod.CreateDelegate(typeof(Func<IDataRecord, T>)) as Func<IDataRecord, T>;
            }
        }

19 View Source File : DynamicParameters.cs
License : MIT License
Project Creator : anet-team

public DynamicParameters Output<T>(T target, Expression<Func<T, object>> expression, DbType? dbType = null, int? size = null)
        {
            var failMessage = "Expression must be a property/field chain off of a(n) {0} instance";
            failMessage = string.Format(failMessage, typeof(T).Name);
            Action @throw = () => throw new InvalidOperationException(failMessage);

            // Is it even a MemberExpression?
            var lastMemberAccess = expression.Body as MemberExpression;

            if (lastMemberAccess == null
                || (!(lastMemberAccess.Member is PropertyInfo)
                    && !(lastMemberAccess.Member is FieldInfo)))
            {
                if (expression.Body.NodeType == ExpressionType.Convert
                    && expression.Body.Type == typeof(object)
                    && ((UnaryExpression)expression.Body).Operand is MemberExpression)
                {
                    // It's got to be unboxed
                    lastMemberAccess = (MemberExpression)((UnaryExpression)expression.Body).Operand;
                }
                else
                {
                    @throw();
                }
            }

            // Does the chain consist of MemberExpressions leading to a ParameterExpression of type T?
            MemberExpression diving = lastMemberAccess;
            // Retain a list of member names and the member expressions so we can rebuild the chain.
            List<string> names = new List<string>();
            List<MemberExpression> chain = new List<MemberExpression>();

            do
            {
                // Insert the names in the right order so expression
                // "Post.Author.Name" becomes parameter "PostAuthorName"
                names.Insert(0, diving?.Member.Name);
                chain.Insert(0, diving);

                var constant = diving?.Expression as ParameterExpression;
                diving = diving?.Expression as MemberExpression;

                if (constant != null && constant.Type == typeof(T))
                {
                    break;
                }
                else if (diving == null
                    || (!(diving.Member is PropertyInfo)
                        && !(diving.Member is FieldInfo)))
                {
                    @throw();
                }
            }
            while (diving != null);

            var dynamicParamName = string.Concat(names.ToArray());

            // Before we get all emitty...
            var lookup = string.Join("|", names.ToArray());

            var cache = CachedOutputSetters<T>.Cache;
            var setter = (Action<object, DynamicParameters>)cache[lookup];
            if (setter != null) goto MAKECALLBACK;

            // Come on let's build a method, let's build it, let's build it now!
            var dm = new DynamicMethod("ExpressionParam" + Guid.NewGuid().ToString(), null, new[] { typeof(object), GetType() }, true);
            var il = dm.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0); // [object]
            il.Emit(OpCodes.Castclreplaced, typeof(T));    // [T]

            // Count - 1 to skip the last member access
            var i = 0;
            for (; i < (chain.Count - 1); i++)
            {
                var member = chain[0].Member;

                if (member is PropertyInfo)
                {
                    var get = ((PropertyInfo)member).GetGetMethod(true);
                    il.Emit(OpCodes.Callvirt, get); // [Member{i}]
                }
                else // Else it must be a field!
                {
                    il.Emit(OpCodes.Ldfld, (FieldInfo)member); // [Member{i}]
                }
            }

            var paramGetter = GetType().GetMethod("Get", new Type[] { typeof(string) }).MakeGenericMethod(lastMemberAccess.Type);

            il.Emit(OpCodes.Ldarg_1); // [target] [DynamicParameters]
            il.Emit(OpCodes.Ldstr, dynamicParamName); // [target] [DynamicParameters] [ParamName]
            il.Emit(OpCodes.Callvirt, paramGetter); // [target] [value], it's already typed thanks to generic method

            // GET READY
            var lastMember = lastMemberAccess.Member;
            if (lastMember is PropertyInfo)
            {
                var set = ((PropertyInfo)lastMember).GetSetMethod(true);
                il.Emit(OpCodes.Callvirt, set); // SET
            }
            else
            {
                il.Emit(OpCodes.Stfld, (FieldInfo)lastMember); // SET
            }

            il.Emit(OpCodes.Ret); // GO

            setter = (Action<object, DynamicParameters>)dm.CreateDelegate(typeof(Action<object, DynamicParameters>));
            lock (cache)
            {
                cache[lookup] = setter;
            }

            // Queue the preparation to be fired off when adding parameters to the DbCommand
            MAKECALLBACK:
            (outputCallbacks ?? (outputCallbacks = new List<Action>())).Add(() =>
            {
                // Finally, prep the parameter and attach the callback to it
                var targetMemberType = lastMemberAccess?.Type;
                int sizeToSet = (!size.HasValue && targetMemberType == typeof(string)) ? DbString.DefaultLength : size ?? 0;

                if (parameters.TryGetValue(dynamicParamName, out ParamInfo parameter))
                {
                    parameter.ParameterDirection = parameter.AttachedParam.Direction = ParameterDirection.InputOutput;

                    if (parameter.AttachedParam.Size == 0)
                    {
                        parameter.Size = parameter.AttachedParam.Size = sizeToSet;
                    }
                }
                else
                {
                    dbType = (!dbType.HasValue)
#pragma warning disable 618
                    ? SqlMapper.LookupDbType(targetMemberType, targetMemberType?.Name, true, out SqlMapper.ITypeHandler handler)
#pragma warning restore 618
                    : dbType;

                    // CameFromTemplate property would not apply here because this new param
                    // Still needs to be added to the command
                    Add(dynamicParamName, expression.Compile().Invoke(target), null, ParameterDirection.InputOutput, sizeToSet);
                }

                parameter = parameters[dynamicParamName];
                parameter.OutputCallback = setter;
                parameter.OutputTarget = target;
            });

            return this;
        }

19 View Source File : TypedReferenceHelpers.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static FieldAdr BuildAddrHelper(FieldInfo field)
        {
            var dm = new DynamicMethod("", typeof(void), new[] {typeof(TypedRefPtr), typeof(TypedRefPtr)}, Unverifier.Module, true);
            var gen = dm.GetILGenerator();

            if(field.IsStatic)
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, 1);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldfld, typedPtrField);

                gen.Emit(System.Reflection.Emit.OpCodes.Ldsflda, field);
                gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, field.FieldType);
                gen.Emit(System.Reflection.Emit.OpCodes.Stobj, typeof(TypedReference));
                gen.Emit(System.Reflection.Emit.OpCodes.Ret);
            }
            else
            {
                gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, 1);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldfld, typedPtrField);

                gen.Emit(System.Reflection.Emit.OpCodes.Ldarga, 0);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldfld, typedPtrField);
                gen.Emit(System.Reflection.Emit.OpCodes.Ldobj, typeof(TypedReference));
                gen.Emit(System.Reflection.Emit.OpCodes.Refanyval, field.DeclaringType);
                if(!field.DeclaringType.IsValueType)
                    gen.Emit(System.Reflection.Emit.OpCodes.Ldobj, field.DeclaringType);

                gen.Emit(System.Reflection.Emit.OpCodes.Ldflda, field);
                gen.Emit(System.Reflection.Emit.OpCodes.Mkrefany, field.FieldType);
                gen.Emit(System.Reflection.Emit.OpCodes.Stobj, typeof(TypedReference));
                gen.Emit(System.Reflection.Emit.OpCodes.Ret);
            }

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

19 View Source File : ArrayStoreHelpers.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static _SetValue BuildStoreHelper(Type valueType, Type elemType)
        {
            var paramTypes = new[] {typeof(Array), typeof(int), typeof(object)};
            var dm = new DynamicMethod("", typeof(void), paramTypes, Unverifier.Module, true);
            var gen = dm.GetILGenerator();

            gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
            gen.Emit(System.Reflection.Emit.OpCodes.Ldarg_2);
            if(elemType.IsValueType)
                gen.Emit(System.Reflection.Emit.OpCodes.Unbox_Any, valueType);
            gen.Emit(System.Reflection.Emit.OpCodes.Stelem, elemType);
            gen.Emit(System.Reflection.Emit.OpCodes.Ret);

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

19 View Source File : EntityMapperProvider.cs
License : Apache License 2.0
Project Creator : 1448376744

private Func<object, Dictionary<string, object>> CreateTypeDeserializerHandler(Type type)
        {
            var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            var methodName = $"{type.Name}Deserializer{Guid.NewGuid():N}";
            var dynamicMethod = new DynamicMethod(methodName, typeof(Dictionary<string, object>), new Type[] { typeof(object) }, type, true);
            var generator = dynamicMethod.GetILGenerator();
            LocalBuilder enreplacedyLocal1 = generator.DeclareLocal(typeof(Dictionary<string, object>));
            LocalBuilder enreplacedyLocal2 = generator.DeclareLocal(type);
            generator.Emit(OpCodes.Newobj, typeof(Dictionary<string, object>).GetConstructor(Type.EmptyTypes));
            generator.Emit(OpCodes.Stloc, enreplacedyLocal1);
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Castclreplaced, type);
            generator.Emit(OpCodes.Stloc, enreplacedyLocal2);
            foreach (var item in properties)
            {
                generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
                generator.Emit(OpCodes.Ldstr, item.Name);
                generator.Emit(OpCodes.Ldloc, enreplacedyLocal2);
                generator.Emit(OpCodes.Callvirt, item.GetGetMethod());
                if (item.PropertyType.IsValueType)
                {
                    generator.Emit(OpCodes.Box, item.PropertyType);
                }
                var addMethod = typeof(Dictionary<string, object>).GetMethod(nameof(Dictionary<string, object>.Add), new Type[] { typeof(string), typeof(object) });
                generator.Emit(OpCodes.Callvirt, addMethod);
            }
            generator.Emit(OpCodes.Ldloc, enreplacedyLocal1);
            generator.Emit(OpCodes.Ret);
            return dynamicMethod.CreateDelegate(typeof(Func<object, Dictionary<string, object>>)) as Func<object, Dictionary<string, object>>;
        }

19 View Source File : Helpers.cs
License : MIT License
Project Creator : 71

internal static TDelegate MakeDelegate<TDelegate>(string name, Action<ILGenerator> ilgen, Type owner = null)
            where TDelegate : Delegate
        {
            MethodInfo invokeMethod = typeof(TDelegate).GetMethod("Invoke");

            Debug.replacedert(invokeMethod != null);

            ParameterInfo[] parameters = invokeMethod.GetParameters();
            Type[] parameterTypes = new Type[parameters.Length];

            for (int i = 0; i < parameters.Length; i++)
            {
                parameterTypes[i] = parameters[i].ParameterType;
            }

            DynamicMethod method = owner == null
                ? new DynamicMethod(name, invokeMethod.ReturnType, parameterTypes, true)
                : new DynamicMethod(name, invokeMethod.ReturnType, parameterTypes, owner, true);

            ILGenerator il = method.GetILGenerator();

            ilgen(il);

            return (TDelegate)method.CreateDelegate(typeof(TDelegate));
        }

19 View Source File : Helper.cs
License : Apache License 2.0
Project Creator : aadreja

internal static Func<object, object> CreateGetProperty(Type enreplacedyType, string propertyName)
        {
            MethodInfo mi = enreplacedyType.GetProperty(propertyName).GetMethod;

            if (mi == null) return null; //no get property

            Type[] args = new Type[] { typeof(object) };

            DynamicMethod method = new DynamicMethod("Get_" + enreplacedyType.Name + "_" + propertyName, typeof(object), args, enreplacedyType.Module, true);
            ILGenerator getIL = method.GetILGenerator();

            getIL.DeclareLocal(typeof(object));
            getIL.Emit(OpCodes.Ldarg_0); //Load the first argument

            //(target object)
            //Cast to the source type
            getIL.Emit(OpCodes.Castclreplaced, enreplacedyType);

            //Get the property value
            getIL.EmitCall(OpCodes.Call, mi, null);
            if (mi.ReturnType.IsValueType)
            {
                getIL.Emit(OpCodes.Box, mi.ReturnType);
                //Box if necessary
            }
            getIL.Emit(OpCodes.Stloc_0); //Store it

            getIL.Emit(OpCodes.Ldloc_0);
            getIL.Emit(OpCodes.Ret);

            var funcType = System.Linq.Expressions.Expression.GetFuncType(typeof(object), typeof(object));
            return (Func<object, object>)method.CreateDelegate(funcType);
        }

19 View Source File : EHHelper.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

private static bool BuildExceptionDispatchInfo(Type type)
        {
            try
            {
                var capture = type.GetMethod("Capture");
                var thr = type.GetMethod("Throw");

                var dm = new DynamicMethod("", typeof(void), new[] {typeof(Exception), typeof(string), typeof(bool)});
                var ilGen = dm.GetILGenerator();
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, capture);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Call, thr);
                ilGen.Emit(System.Reflection.Emit.OpCodes.Ret);

                rethrow = (Throw) dm.CreateDelegate(typeof(Throw));
            }
            catch
            {
                return false;
            }
            return true;
        }

19 View Source File : DynamicReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
        {
            DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString(), typeof(object), new[] { typeof(object[]) }, method.DeclaringType);
            ILGenerator generator = dynamicMethod.GetILGenerator();

            GenerateCreateMethodCallIL(method, generator, 0);

            return (ObjectConstructor<object>)dynamicMethod.CreateDelegate(typeof(ObjectConstructor<object>));
        }

See More Examples