System.Reflection.Emit.ILGenerator.Emit(System.Reflection.Emit.OpCode, System.Type)

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

680 Examples 7

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 : ReflectionHandlerFactory.cs
License : MIT License
Project Creator : aquilahkj

private static void EmitBoxIfNeeded(ILGenerator il, Type type)
        {
            if (type.GetTypeInfo().IsValueType)
            {
                il.Emit(OpCodes.Box, type);
            }
        }

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 : ILGeneratorExtensions.cs
License : Apache License 2.0
Project Creator : allenai

public static void EmitUnboxOrCast(this ILGenerator il, Type type)
        {
            if (type.GetTypeInfo().IsValueType)
            {
                il.Emit(OpCodes.Unbox_Any, type);
            }
            else
            {
                il.Emit(OpCodes.Castclreplaced, type);
            }
        }

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

private void GenerateCreateMethodCallIL(MethodBase method, ILGenerator generator, int argsIndex)
        {
            ParameterInfo[] args = method.GetParameters();

            Label argsOk = generator.DefineLabel();

            // throw an error if the number of argument values doesn't match method parameters
            generator.Emit(OpCodes.Ldarg, argsIndex);
            generator.Emit(OpCodes.Ldlen);
            generator.Emit(OpCodes.Ldc_I4, args.Length);
            generator.Emit(OpCodes.Beq, argsOk);
            generator.Emit(OpCodes.Newobj, typeof(TargetParameterCountException).GetConstructor(ReflectionUtils.EmptyTypes));
            generator.Emit(OpCodes.Throw);

            generator.MarkLabel(argsOk);

            if (!method.IsConstructor && !method.IsStatic)
            {
                generator.PushInstance(method.DeclaringType);
            }

            int localVariableCount = 0;

            for (int i = 0; i < args.Length; i++)
            {
                ParameterInfo parameter = args[i];
                Type parameterType = parameter.ParameterType;

                if (parameterType.IsByRef)
                {
                    parameterType = parameterType.GetElementType();

                    LocalBuilder localVariable = generator.DeclareLocal(parameterType);

                    // don't need to set variable for 'out' parameter
                    if (!parameter.IsOut)
                    {
                        generator.PushArrayInstance(argsIndex, i);

                        if (parameterType.IsValueType())
                        {
                            Label skipSettingDefault = generator.DefineLabel();
                            Label finishedProcessingParameter = generator.DefineLabel();

                            // check if parameter is not null
                            generator.Emit(OpCodes.Brtrue_S, skipSettingDefault);

                            // parameter has no value, initialize to default
                            generator.Emit(OpCodes.Ldloca_S, localVariable);
                            generator.Emit(OpCodes.Initobj, parameterType);
                            generator.Emit(OpCodes.Br_S, finishedProcessingParameter);

                            // parameter has value, get value from array again and unbox and set to variable
                            generator.MarkLabel(skipSettingDefault);
                            generator.PushArrayInstance(argsIndex, i);
                            generator.UnboxIfNeeded(parameterType);
                            generator.Emit(OpCodes.Stloc, localVariableCount);

                            // parameter finished, we out!
                            generator.MarkLabel(finishedProcessingParameter);
                        }
                        else
                        {
                            generator.UnboxIfNeeded(parameterType);
                            generator.Emit(OpCodes.Stloc, localVariableCount);
                        }
                    }

                    generator.Emit(OpCodes.Ldloca_S, localVariable);

                    localVariableCount++;
                }
                else if (parameterType.IsValueType())
                {
                    generator.PushArrayInstance(argsIndex, i);

                    // have to check that value type parameters aren't null
                    // otherwise they will error when unboxed
                    Label skipSettingDefault = generator.DefineLabel();
                    Label finishedProcessingParameter = generator.DefineLabel();

                    // check if parameter is not null
                    generator.Emit(OpCodes.Brtrue_S, skipSettingDefault);

                    // parameter has no value, initialize to default
                    LocalBuilder localVariable = generator.DeclareLocal(parameterType);
                    generator.Emit(OpCodes.Ldloca_S, localVariable);
                    generator.Emit(OpCodes.Initobj, parameterType);
                    generator.Emit(OpCodes.Ldloc, localVariableCount);
                    generator.Emit(OpCodes.Br_S, finishedProcessingParameter);

                    // parameter has value, get value from array again and unbox
                    generator.MarkLabel(skipSettingDefault);
                    generator.PushArrayInstance(argsIndex, i);
                    generator.UnboxIfNeeded(parameterType);

                    // parameter finished, we out!
                    generator.MarkLabel(finishedProcessingParameter);
                    localVariableCount++;
                }
                else
                {
                    generator.PushArrayInstance(argsIndex, i);

                    generator.UnboxIfNeeded(parameterType);
                }
            }

            if (method.IsConstructor)
            {
                generator.Emit(OpCodes.Newobj, (ConstructorInfo)method);
            }
            else
            {
                generator.CallMethod((MethodInfo)method);
            }

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

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

            generator.Return();
        }

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 : ILExtensions.cs
License : MIT License
Project Creator : aloneguid

public static void GetArrayElement(this ILGenerator il, LocalBuilder array, LocalBuilder index, bool loadByRef, Type elementType, LocalBuilder elementReceiver)
      {
         //load data element
         il.Emit(Ldloc, array.LocalIndex);  //data array
         il.Emit(Ldloc, index.LocalIndex);  //index
         if (loadByRef)
         {
            il.Emit(Ldelem_Ref);
         }
         else
         {
            il.Emit(Ldelem, elementType);
         }
         il.Emit(Stloc, elementReceiver.LocalIndex);  //data value
      }

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 : ILCompiler.cs
License : MIT License
Project Creator : badamczewski

public ILCompilationUnit Compile(string il)
        {
            ILTokenizer tokenizer = new ILTokenizer();
            ILParser iLParser = new ILParser();

            var tokens = tokenizer.Tokenize(il);
            var root = iLParser.Parse(tokens);

            if (root.Errors.Count > 0)
            {
                return new ILCompilationUnit() { Errors = root.Errors };
            }

            var name = Guid.NewGuid().ToString();
            var asm  = replacedemblyBuilder.DefineDynamicreplacedembly(
                new replacedemblyName(name),
                replacedemblyBuilderAccess.Run);

            var module = asm.DefineDynamicModule(name);
            var type = module.DefineType("Compilation", TypeAttributes.Public | TypeAttributes.BeforeFieldInit);

            foreach (var ilMethod in root.Clreplacedes.First().Methods)
            {
                var returnType = StringToType(ilMethod.Returns);
               
                Type[] argTypes = new Type[ilMethod.Args.Count];
                int idx = 0;
                foreach(var arg in ilMethod.Args)
                {
                    argTypes[idx++] = StringToType(arg.Type);
                }

                int indexOffset = 1;
                MethodAttributes attributes = MethodAttributes.Public;
                if (ilMethod.Accessor == "private")
                {
                    attributes = MethodAttributes.Private;
                }

                if (ilMethod.InstanceType == "static")
                {
                    attributes |= MethodAttributes.Static;
                    indexOffset = 0;
                }

                var method = type.DefineMethod(ilMethod.Name, attributes | MethodAttributes.HideBySig, returnType, argTypes);
                var ilGen  = method.GetILGenerator();


                //
                // Book keep the labels 
                //
                Label[] labels = new Label[ilMethod.Code.Count];
                int opCodeindex = 0;

                foreach (var opCode in ilMethod.Code)
                {
                    var label = default(Label);  

                    if (labels[opCodeindex] == default(Label))
                    {
                        label = ilGen.DefineLabel();
                    }
                    else
                    {
                        label = labels[opCodeindex];
                    }

                    ilGen.MarkLabel(label);


                    switch (opCode.OpCode)
                    {
                        //
                        // Consts and Loads
                        //
                        case "ldc.i4.0": ilGen.Emit(OpCodes.Ldc_I4_0); break;
                        case "ldc.i4.1": ilGen.Emit(OpCodes.Ldc_I4_1); break;
                        case "ldc.i4.2": ilGen.Emit(OpCodes.Ldc_I4_2); break;
                        case "ldc.i4.3": ilGen.Emit(OpCodes.Ldc_I4_3); break;
                        case "ldc.i4.4": ilGen.Emit(OpCodes.Ldc_I4_4); break;
                        case "ldc.i4.5": ilGen.Emit(OpCodes.Ldc_I4_5); break;
                        case "ldc.i4.6": ilGen.Emit(OpCodes.Ldc_I4_6); break;
                        case "ldc.i4.7": ilGen.Emit(OpCodes.Ldc_I4_7); break;
                        case "ldc.i4.8": ilGen.Emit(OpCodes.Ldc_I4_8); break;
                        case "ldc.i4.s": ilGen.Emit(OpCodes.Ldc_I4_S,  int.Parse(opCode.GetFirstArg())); break;
                        case "ldc.i4":   ilGen.Emit(OpCodes.Ldc_I4,    int.Parse(opCode.GetFirstArg())); break;
                        case "ldarg.0":  ilGen.Emit(OpCodes.Ldarg_0);  break;
                        case "ldarg.1":  ilGen.Emit(OpCodes.Ldarg_1);  break;
                        case "ldarg.2":  ilGen.Emit(OpCodes.Ldarg_2);  break;
                        case "ldarg.3":  ilGen.Emit(OpCodes.Ldarg_3);  break;
                        case "ldarg.s":  ilGen.Emit(OpCodes.Ldarg_S,   FindArgIndex(opCode.GetFirstArg(), ilMethod, indexOffset)); break;
                        case "ldarga.s": ilGen.Emit(OpCodes.Ldarga_S,  FindArgIndex(opCode.GetFirstArg(), ilMethod, indexOffset)); break;
                        case "starg.s":  ilGen.Emit(OpCodes.Starg_S,   FindArgIndex(opCode.GetFirstArg(), ilMethod, indexOffset)); break;
                        case "starg":    ilGen.Emit(OpCodes.Starg,     FindArgIndex(opCode.GetFirstArg(), ilMethod, indexOffset)); break;

                        //
                        // Stringsssss
                        //
                        case "ldstr":    ilGen.Emit(OpCodes.Ldstr, opCode.GetFirstArg()); break;


                        //
                        // Conditions
                        //

                        // !=
                        case "bne.un.s":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Bne_Un_S, existing); break;
                            }
                        case "bne.un":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Bne_Un, existing); break;
                            }
                        // ==
                        case "beq.s":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Beq_S, existing); break;
                            }
                        case "beq":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Beq, existing); break;
                            }
                        // >=
                        case "bge.s":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Bge_S, existing); break;
                            }
                        case "bge":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Bge, existing); break;
                            }
                        // <=
                        case "ble.s":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Ble_S, existing); break;
                            }
                        case "ble":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Ble, existing); break;
                            }
                        // <
                        case "blt.s":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Blt_S, existing); break;
                            }
                        case "blt":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Blt, existing); break;
                            }
                        // >
                        case "bgt.s":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Bgt_S, existing); break;
                            }
                        case "bgt":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Bgt, existing); break;
                            }
                        // Unconditional Jump
                        case "br.s":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Br_S, existing); break;
                            }
                        case "br":
                            {
                                var existing = GetOrCreateLabel(ilGen, labels, opCode, ilMethod);
                                ilGen.Emit(OpCodes.Br, existing); break;
                            }
                        case "stelem.i1": ilGen.Emit(OpCodes.Stelem_I1); break;
                        case "stelem.i2": ilGen.Emit(OpCodes.Stelem_I2); break;
                        case "stelem.i4": ilGen.Emit(OpCodes.Stelem_I4); break;
                        case "stelem.i8": ilGen.Emit(OpCodes.Stelem_I8); break;
                        case "stelem.r4": ilGen.Emit(OpCodes.Stelem_R4); break;
                        case "stelem.r8": ilGen.Emit(OpCodes.Stelem_R8); break;

                        //
                        // Boxing / Unboxing
                        //
                        case "box":       ilGen.Emit(OpCodes.Box,       StringToType(opCode.GetFirstArg())); break;
                        case "unbox.any": ilGen.Emit(OpCodes.Unbox_Any, StringToType(opCode.GetFirstArg())); break;
                        case "unbox":     ilGen.Emit(OpCodes.Unbox,     StringToType(opCode.GetFirstArg())); break;
                        //
                        // Switch / Case
                        //
                        case "switch":    ilGen.Emit(OpCodes.Switch, GetOrCreateLabels(ilGen, labels, opCode, ilMethod)); break;
                        //
                        // Call
                        // This needs better handling; we want to call methods we have defined in IL
                        // so to do this we first would need to figure out which one to emit first.
                        //
                        case "call":     ilGen.Emit(OpCodes.Call,     CreateCall((ILCallInst)opCode)); break;
                        case "callvirt": ilGen.Emit(OpCodes.Callvirt, CreateCall((ILCallInst)opCode)); break;
                        //
                        // Maths 
                        //
                        case "sub":      ilGen.Emit(OpCodes.Sub); break;
                        case "mul":      ilGen.Emit(OpCodes.Mul); break;
                        case "div":      ilGen.Emit(OpCodes.Div); break;
                        case "add":      ilGen.Emit(OpCodes.Add); break;
                        case "ret":      ilGen.Emit(OpCodes.Ret); break;
                    }

                    opCodeindex++;
                }
            }

            return new ILCompilationUnit() { CompiledType = type.CreateType() };
        }

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 : 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 : ILGeneratorExtensions.cs
License : MIT License
Project Creator : akaskela

public static void PushInstance(this ILGenerator generator, Type type)
        {
            generator.Emit(OpCodes.Ldarg_0);
            if (type.IsValueType())
            {
                generator.Emit(OpCodes.Unbox, type);
            }
            else
            {
                generator.Emit(OpCodes.Castclreplaced, type);
            }
        }

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 : 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 : ReaderCache.cs
License : Apache License 2.0
Project Creator : aadreja

private static void ConvertValueToEnum(ILGenerator il, Type from, Type to, Type via)
        {
            MethodInfo op;
            if (from == (via ?? to))
            {
                il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
            }
            else if ((op = GetOperator(from, to)) != null)
            {
                // this is handy for things like decimal <===> double
                il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][data-typed-value]
                il.Emit(OpCodes.Call, op); // stack is now [target][target][typed-value]
            }
            else
            {
                bool handled = false;
                OpCode opCode = default;
                switch (Type.GetTypeCode(from))
                {
                    case TypeCode.Boolean:
                    case TypeCode.Byte:
                    case TypeCode.SByte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.Int32:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                    case TypeCode.Single:
                    case TypeCode.Double:
                        handled = true;
                        switch (Type.GetTypeCode(via ?? to))
                        {
                            case TypeCode.Byte:
                                opCode = OpCodes.Conv_Ovf_I1_Un; break;
                            case TypeCode.SByte:
                                opCode = OpCodes.Conv_Ovf_I1; break;
                            case TypeCode.UInt16:
                                opCode = OpCodes.Conv_Ovf_I2_Un; break;
                            case TypeCode.Int16:
                                opCode = OpCodes.Conv_Ovf_I2; break;
                            case TypeCode.UInt32:
                                opCode = OpCodes.Conv_Ovf_I4_Un; break;
                            case TypeCode.Boolean: // boolean is basically an int, at least at this level
                            case TypeCode.Int32:
                                opCode = OpCodes.Conv_Ovf_I4; break;
                            case TypeCode.UInt64:
                                opCode = OpCodes.Conv_Ovf_I8_Un; break;
                            case TypeCode.Int64:
                                opCode = OpCodes.Conv_Ovf_I8; break;
                            case TypeCode.Single:
                                opCode = OpCodes.Conv_R4; break;
                            case TypeCode.Double:
                                opCode = OpCodes.Conv_R8; break;
                            default:
                                handled = false;
                                break;
                        }
                        break;
                }
                if (handled)
                {
                    il.Emit(OpCodes.Unbox_Any, from); // stack is now [target][target][col-typed-value]
                    il.Emit(opCode); // stack is now [target][target][typed-value]
                    if (to == typeof(bool))
                    { // compare to zero; I checked "csc" - this is the trick it uses; nice
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                        il.Emit(OpCodes.Ldc_I4_0);
                        il.Emit(OpCodes.Ceq);
                    }
                }
                else
                {
                    il.Emit(OpCodes.Ldtoken, via ?? to); // stack is now [target][target][value][member-type-token]
                    il.EmitCall(OpCodes.Call, typeof(Type).GetMethod(nameof(Type.GetTypeFromHandle)), null); // stack is now [target][target][value][member-type]
                    il.EmitCall(OpCodes.Call, typeof(Convert).GetMethod(nameof(Convert.ChangeType), new Type[] { typeof(object), typeof(Type) }), null); // stack is now [target][target][boxed-member-type-value]
                    il.Emit(OpCodes.Unbox_Any, to); // stack is now [target][target][typed-value]
                }
            }
        }

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

public static IDisposable ForEachLoop(this ILGenerator il, Type elementType, LocalBuilder collection, out LocalBuilder currentElement)
      {
         Label lMoveNext = il.DefineLabel();
         Label lWork = il.DefineLabel();
         currentElement = il.DeclareLocal(elementType);

         //get collection enumerator
         LocalBuilder enumerator = il.DeclareLocal(typeof(IEnumerator));
#if DEBUG
         il.EmitWriteLine("foreach-begin");
#endif
         il.Emit(Ldloc, collection.LocalIndex);
         il.Emit(Callvirt, getEnumeratorMethod);
         il.Emit(Stloc, enumerator.LocalIndex);

         //immediately move to "move next" to start enumeration
         il.Emit(Br, lMoveNext);

         //iteration work block
         il.MarkLabel(lWork);
#if DEBUG
         il.EmitWriteLine("  foreach-loop");
#endif

         //get current element
         il.Emit(Ldloc, enumerator.LocalIndex);
         il.Emit(Callvirt, getCurrentMethod);
         il.Emit(Unbox_Any, elementType);
         il.Emit(Stloc, currentElement.LocalIndex);

         return il.After(() =>
         {
            //"move next" block
            il.MarkLabel(lMoveNext);
            il.Emit(Ldloc, enumerator.LocalIndex);  //load enumerator as an argument
            il.Emit(Callvirt, moveNextMethod);
            il.Emit(Brtrue, lWork);   //if result is true, go to lWork

            //otherwise, dispose enumerator and exit
            //il.Emit(Ldloc, enumerator.LocalIndex);
            //il.Emit(Callvirt, disposeMethod);
#if DEBUG
            il.EmitWriteLine("foreach-end");
#endif
         });
      }

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 : 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 : 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 : AssertExtend.cs
License : MIT License
Project Creator : aquilahkj

private static void EmitBoxIfNeeded(ILGenerator il, Type type)
            {
                if (type.GetTypeInfo().IsValueType) {
                    il.Emit(OpCodes.Box, type);
                }
            }

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 : 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 : 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 : DynamicReflectionDelegateFactory.cs
License : MIT License
Project Creator : akaskela

private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator)
        {
            if (type.IsValueType())
            {
                generator.DeclareLocal(type);
                generator.Emit(OpCodes.Ldloc_0);
                generator.Emit(OpCodes.Box, type);
            }
            else
            {
                ConstructorInfo constructorInfo =
                    type.GetConstructor(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null,
                        ReflectionUtils.EmptyTypes, null);

                if (constructorInfo == null)
                {
                    throw new ArgumentException("Could not get constructor for {0}.".FormatWith(CultureInfo.InvariantCulture, type));
                }

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

            generator.Return();
        }

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 : 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 : ILGeneratorExtensions.cs
License : MIT License
Project Creator : akaskela

public static void BoxIfNeeded(this ILGenerator generator, Type type)
        {
            if (type.IsValueType())
            {
                generator.Emit(OpCodes.Box, type);
            }
            else
            {
                generator.Emit(OpCodes.Castclreplaced, type);
            }
        }

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 : 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 : 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 : ILGeneratorExtensions.cs
License : Apache License 2.0
Project Creator : allenai

public static void EmitBoxOrDoNothing(this ILGenerator il, Type type)
        {
            if (type.GetTypeInfo().IsValueType)
            {
                il.Emit(OpCodes.Box, type);
            }
        }

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 : 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 : EmitHelper.cs
License : MIT License
Project Creator : 1996v

public static void EmitObjectConvertTo(this ILGenerator il, Type target)
        {
            if (target != typeof(object))
            {
                if (target.IsValueType)
                {
                    il.Emit(OpCodes.Unbox_Any, target);
                }
                else
                {
                    il.Emit(OpCodes.Castclreplaced, target);
                }
            }
        }

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

public static IDisposable ForEachLoopFromEnumerator(this ILGenerator il, Type elementType, LocalBuilder enumerator, out LocalBuilder currentElement)
      {
         Label lMoveNext = il.DefineLabel();
         Label lWork = il.DefineLabel();
         currentElement = il.DeclareLocal(elementType);

#if DEBUG
         il.EmitWriteLine("foreach-begin");
#endif

         //immediately move to "move next" to start enumeration
         il.Emit(Br, lMoveNext);

         //iteration work block
         il.MarkLabel(lWork);
#if DEBUG
         il.EmitWriteLine("  foreach-loop");
#endif

         //get current element
         il.Emit(Ldloc, enumerator.LocalIndex);
         il.Emit(Callvirt, getCurrentMethod);
         il.Emit(Unbox_Any, elementType);
         il.Emit(Stloc, currentElement.LocalIndex);

         return il.After(() =>
         {
            //"move next" block
            il.MarkLabel(lMoveNext);
            il.Emit(Ldloc, enumerator.LocalIndex);  //load enumerator as an argument
            il.Emit(Callvirt, moveNextMethod);
            il.Emit(Brtrue, lWork);   //if result is true, go to lWork

            //otherwise, dispose enumerator and exit
            //il.Emit(Ldloc, enumerator.LocalIndex);
            //il.Emit(Callvirt, disposeMethod);
#if DEBUG
            il.EmitWriteLine("foreach-end");
#endif
         });
      }

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 : ILExtensions.cs
License : MIT License
Project Creator : aloneguid

public static void GetArrayElement(this ILGenerator il, OpCode loadArrayCode, LocalBuilder index, bool loadByRef, Type elementType, LocalBuilder elementReceiver)
      {
         //load data element
         il.Emit(loadArrayCode);  //data array
         il.Emit(Ldloc, index.LocalIndex);  //index
         if (loadByRef)
         {
            il.Emit(Ldelem_Ref);
         }
         else
         {
            il.Emit(Ldelem, elementType);
         }
         il.Emit(Stloc, elementReceiver.LocalIndex);  //data value
      }

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 : 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 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 : ReflectionHandlerFactory.cs
License : MIT License
Project Creator : aquilahkj

private static FastMethodHandler CreateMethodHandler(MethodInfo methodInfo)
        {
            int num;
            var method = new DynamicMethod(string.Empty, typeof(object), new[]
            {
                typeof(object),
                typeof(object[])
            }, methodInfo.DeclaringType.GetTypeInfo().Module);
            var iLGenerator = method.GetILGenerator();
            var parameters = methodInfo.GetParameters();
            var typeArray = new Type[parameters.Length];
            for (num = 0; num < typeArray.Length; num++)
            {
                if (parameters[num].ParameterType.IsByRef)
                {
                    typeArray[num] = parameters[num].ParameterType.GetElementType();
                }
                else
                {
                    typeArray[num] = parameters[num].ParameterType;
                }
            }

            var builderArray = new LocalBuilder[typeArray.Length];
            for (num = 0; num < typeArray.Length; num++)
            {
                builderArray[num] = iLGenerator.DeclareLocal(typeArray[num], true);
            }

            for (num = 0; num < typeArray.Length; num++)
            {
                iLGenerator.Emit(OpCodes.Ldarg_1);
                EmitFastInt(iLGenerator, num);
                iLGenerator.Emit(OpCodes.Ldelem_Ref);
                EmitCastToReference(iLGenerator, typeArray[num]);
                iLGenerator.Emit(OpCodes.Stloc, builderArray[num]);
            }

            if (!methodInfo.IsStatic)
            {
                iLGenerator.Emit(OpCodes.Ldarg_0);
            }

            for (num = 0; num < typeArray.Length; num++)
            {
                iLGenerator.Emit(parameters[num].ParameterType.IsByRef ? OpCodes.Ldloca_S : OpCodes.Ldloc,
                    builderArray[num]);
            }

            iLGenerator.EmitCall(methodInfo.IsStatic ? OpCodes.Call : OpCodes.Callvirt, methodInfo, null);
            if (methodInfo.ReturnType == typeof(void))
            {
                iLGenerator.Emit(OpCodes.Ldnull);
            }
            else
            {
                EmitBoxIfNeeded(iLGenerator, methodInfo.ReturnType);
            }

            for (num = 0; num < typeArray.Length; num++)
            {
                if (parameters[num].ParameterType.IsByRef)
                {
                    iLGenerator.Emit(OpCodes.Ldarg_1);
                    EmitFastInt(iLGenerator, num);
                    iLGenerator.Emit(OpCodes.Ldloc, builderArray[num]);
                    if (builderArray[num].LocalType.GetTypeInfo().IsValueType)
                    {
                        iLGenerator.Emit(OpCodes.Box, builderArray[num].LocalType);
                    }

                    iLGenerator.Emit(OpCodes.Stelem_Ref);
                }
            }

            iLGenerator.Emit(OpCodes.Ret);
            return (FastMethodHandler) method.CreateDelegate(typeof(FastMethodHandler));
        }

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 : ReflectionHandlerFactory.cs
License : MIT License
Project Creator : aquilahkj

private static void EmitCastToReference(ILGenerator il, Type type)
        {
            il.Emit(type.GetTypeInfo().IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclreplaced, type);
        }

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 : 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 : 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 : EmitHelper.cs
License : MIT License
Project Creator : 1996v

public static void EmitDefault(this ILGenerator il, Type type)
        {
            switch (Type.GetTypeCode(type))
            {
                case TypeCode.DateTime:
                    il.Emit(OpCodes.Ldsfld, typeof(DateTime).GetField(nameof(DateTime.MinValue)));
                    return;
                case TypeCode.Decimal:
                    il.Emit(OpCodes.Ldsfld, typeof(decimal).GetField(nameof(decimal.Zero)));
                    return;
                case TypeCode.Boolean:
                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.Int16:
                case TypeCode.UInt16:
                case TypeCode.Int32:
                case TypeCode.UInt32:
                    il.Emit(OpCodes.Ldc_I4_0);
                    return;

                case TypeCode.Int64:
                case TypeCode.UInt64:
                    il.Emit(OpCodes.Ldc_I4_0);
                    il.Emit(OpCodes.Conv_I8);
                    return;

                case TypeCode.Single:
                    il.Emit(OpCodes.Ldc_R4, default(float));
                    return;

                case TypeCode.Double:
                    il.Emit(OpCodes.Ldc_R8, default(double));
                    return;
            }

            if (type.IsValueType)
            {
                LocalBuilder lb = il.DeclareLocal(type);
                il.Emit(OpCodes.Ldloca, lb);
                il.Emit(OpCodes.Initobj, type);
                il.Emit(OpCodes.Ldloc, lb);
            }
            else
            {
                il.Emit(OpCodes.Ldnull);
            }
        }

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 : 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 : ILGeneratorExtensions.cs
License : MIT License
Project Creator : akaskela

public static void UnboxIfNeeded(this ILGenerator generator, Type type)
        {
            if (type.IsValueType())
            {
                generator.Emit(OpCodes.Unbox_Any, type);
            }
            else
            {
                generator.Emit(OpCodes.Castclreplaced, type);
            }
        }

See More Examples