示例#1
0
文件: test.cs 项目: mono/gert
	static bool DoLdelem ()
	{
		DynamicMethod dm = new DynamicMethod ("EmittedLdelem", typeof (int), null, typeof (Testcase));
		ILGenerator il = dm.GetILGenerator ();
		il.Emit (OpCodes.Ldsfld, ArrayFI);
		il.Emit (OpCodes.Ldc_I4_1);
		il.Emit (OpCodes.Ldelem, typeof (int));
		il.Emit (OpCodes.Ret);
		int i = (int) dm.Invoke (null, null);
		return (i == 2);
	}
        internal static Task RaiseEventAsync <TSender, TEventArgs>(string eventName, TSender sender, TEventArgs eventArgs, Dictionary <string, List <DelegateWrapper> > delegateWrapperDict) where TSender : class where TEventArgs : class
        {
            if (!delegateWrapperDict.TryGetValue(eventName, out List <DelegateWrapper> wrappers))
            {
                return(Task.CompletedTask);
            }

            List <DelegateWrapper>      toRemoves = new List <DelegateWrapper>();
            List <(object, MethodInfo)> toRaises  = new List <(object, MethodInfo)>();

            foreach (DelegateWrapper wrapper in wrappers)
            {
                object caller = wrapper.CallerWeakReference?.Target;

                if (wrapper.CallerWeakReference != null && caller == null)
                {
                    toRemoves.Add(wrapper);
                }
                else
                {
                    toRaises.Add((caller, wrapper.Handler));
                }
            }

            //clean
            toRemoves.ForEach(w => wrappers.Remove(w));

            List <Task> tasks = new List <Task>();

            //Invoke
            for (int i = 0; i < toRaises.Count; ++i)
            {
                (object caller, MethodInfo methodInfo) = toRaises[i];

                object rtObj;

                if (methodInfo.IsLightweightMethod())
                {
                    DynamicMethod dynamicMethodInfo = TryGetDynamicMethod(methodInfo);
                    rtObj = dynamicMethodInfo?.Invoke(caller, new object[] { sender, eventArgs });
                }
                else
                {
                    rtObj = methodInfo.Invoke(caller, new object[] { sender, eventArgs });
                }

                Task task = (Task)rtObj;

                tasks.Add(task);
            }

            return(Task.WhenAll(tasks));
        }
示例#3
0
文件: test.cs 项目: mono/gert
	static bool DoStelem ()
	{
		DynamicMethod dm = new DynamicMethod ("EmittedStelem", null, null, typeof (Testcase));
		ILGenerator il = dm.GetILGenerator ();
		il.Emit (OpCodes.Ldsfld, ArrayFI);
		il.Emit (OpCodes.Ldc_I4_0);
		il.Emit (OpCodes.Ldc_I4_0);
		il.Emit (OpCodes.Stelem, typeof (int));
		il.Emit (OpCodes.Ret);
		dm.Invoke (null, null);
		return (Array [0] == 0);
	}
示例#4
0
	public static int Main()
	{

		DynamicMethod method_builder = new DynamicMethod ("WriteHello" , typeof (int), new Type[] {typeof (Driver)}, typeof (Driver));
		ILGenerator ilg = method_builder.GetILGenerator ();

		ilg.Emit (OpCodes.Ldarg_0);
		ilg.Emit (OpCodes.Call, typeof (Driver).GetMethod ("Foo"));
		ilg.Emit (OpCodes.Ret);

		int res = (int) method_builder.Invoke (null, new object[] {new Driver()});
		return res == -99 ? 0 : 1;
	}
 public static int Main()
 {
     DynamicMethod
     method_builder
     =
     new
     DynamicMethod
     ("ThrowException"
     ,
     typeof
     (void),
     new
     Type[0],
     typeof
     (Driver));
     ILGenerator
     ilg
     =
     method_builder.GetILGenerator
     ();
     ilg.Emit
     (OpCodes.Newobj,
     typeof
     (MyException).GetConstructor
     (new
     Type[0]));
     ilg.Emit
     (OpCodes.Throw);
     try
     {
     method_builder.Invoke
     (null,
     null);
     return
     2;
     }
     catch
     (TargetInvocationException
     tie)
     {
     if(!
     (tie.InnerException
     is
     MyException))
     return
     3;
     }
     return
     0;
 }
    static void M1()
    {
        DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(void), new Type[] { }, typeof(Program), false);

        ILGenerator il = dm.GetILGenerator();

        TestShowVisualizer(dm);
        il.Emit(OpCodes.Ldstr, "hello, world");
        TestShowVisualizer(dm);
        il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }));
        TestShowVisualizer(dm);
        il.Emit(OpCodes.Ret);
        TestShowVisualizer(dm);
        dm.Invoke(null, null);
    }
示例#7
0
        [Test]         // bug #78253
        public void DynamicMethodReference()
        {
            DynamicMethod hello = new DynamicMethod("Hello",
                                                    typeof(int),
                                                    new Type[] { typeof(string) },
                                                    typeof(DynamicMethodTest).Module);

            Assert.IsNull(hello.DeclaringType, "#1");

            DynamicMethod write = new DynamicMethod("Write",
                                                    typeof(int),
                                                    new Type[] { typeof(string) },
                                                    typeof(DynamicMethodTest));

            Assert.IsNull(hello.DeclaringType, "#2");

            MethodInfo invokeWrite = write.GetBaseDefinition();

            ILGenerator helloIL = hello.GetILGenerator();

            helloIL.Emit(OpCodes.Ldarg_0);
            helloIL.EmitCall(OpCodes.Call, invokeWrite, null);
            helloIL.Emit(OpCodes.Ret);

            ILGenerator writeIL = write.GetILGenerator();

            writeIL.Emit(OpCodes.Ldc_I4_2);
            writeIL.Emit(OpCodes.Ret);

            HelloInvoker hi =
                (HelloInvoker)hello.CreateDelegate(typeof(HelloInvoker));
            int ret = hi("Hello, World!");

            Assert.AreEqual(2, ret, "#3");

            object[] invokeArgs = { "Hello, World!" };
            object   objRet     = hello.Invoke(null, invokeArgs);

            Assert.AreEqual(2, objRet, "#4");
        }
        static void Main(string[] args)
        {
            var         dynMethod = new DynamicMethod("HelloMethod", null, null);
            ILGenerator gen       = dynMethod.GetILGenerator();

            gen.EmitWriteLine("Hello world");
            gen.Emit(OpCodes.Ret);
            dynMethod.Invoke(null, null);

            AssemblyName name = new AssemblyName("DynamicAssembly");
            //AssemblyBuilder assemblyBuilder= AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.RunAndSave);
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);

            //ModuleBuilder moduleBuilder= assemblyBuilder.DefineDynamicModule("DynamicModule", "DynamicAssembly.dll");
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");
            TypeBuilder   tb            = moduleBuilder.DefineType("HelloClass", TypeAttributes.Class | TypeAttributes.Public);

            MethodBuilder mb = tb.DefineMethod("PrintHello", MethodAttributes.Public, null, new Type[] { typeof(string) });

            ILGenerator myMethodIL = mb.GetILGenerator();

            myMethodIL.Emit(OpCodes.Ldstr, "Hello ");
            myMethodIL.Emit(OpCodes.Ldarg_1);
            MethodInfo concatMethod = typeof(String).GetMethod("Concat", new Type[] { typeof(string), typeof(string) });

            myMethodIL.Emit(OpCodes.Call, concatMethod);
            MethodInfo writeMethod = typeof(Console).GetMethod("Write", new Type[] { typeof(string) });

            myMethodIL.Emit(OpCodes.Call, writeMethod);
            myMethodIL.Emit(OpCodes.Ret);

            Type helloType = tb.CreateType();

            object     helloObj            = Activator.CreateInstance(helloType);
            MethodInfo helloInstanceMethod = helloType.GetMethod("PrintHello", new Type[] { typeof(string) });

            helloInstanceMethod.Invoke(helloObj, new object[] { "Antonio" });

            //assemblyBuilder.Save("DynamicAssembly.dll");
        }
示例#9
0
        public void GetTokenFor_CtorMethodAndField_Success()
        {
            DynamicMethod dynamicMethod = new DynamicMethod(nameof(Mock), typeof(Person), new Type[] { }, typeof(DynamicILInfoTests), false);
            DynamicILInfo dynamicILInfo = dynamicMethod.GetDynamicILInfo();

            SignatureHelper sigHelper = SignatureHelper.GetLocalVarSigHelper();

            sigHelper.AddArgument(typeof(Person), false);
            sigHelper.AddArgument(typeof(Person), false);
            dynamicILInfo.SetLocalSignature(sigHelper.GetSignature());

            byte[] code =
            {
                0x00, 0x72, 0x49, 0x00, 0x00, 0x70, 0x1f, 0x32, 0x22, 0x00, 0x60, 0xea, 0x46, 0x73, 0x0f, 0x00,
                0x00, 0x06, 0x0a, 0x06, 0x72, 0x53, 0x00, 0x00, 0x70, 0x7d, 0x04, 0x00, 0x00, 0x04, 0x06, 0x25,
                0x6f, 0x0c, 0x00, 0x00, 0x06, 0x17, 0x58, 0x6f, 0x0d, 0x00, 0x00, 0x06, 0x00, 0x06, 0x22, 0x00,
                0x00, 0x96, 0x43, 0x6f, 0x10, 0x00, 0x00, 0x06, 0x00, 0x06, 0x0b, 0x2b, 0x00, 0x07, 0x2a
            };
            int token0 = dynamicILInfo.GetTokenFor("Bill");
            int token1 = dynamicILInfo.GetTokenFor(typeof(Person).GetConstructor(new Type[] { typeof(string), typeof(int), typeof(float) }).MethodHandle);
            int token2 = dynamicILInfo.GetTokenFor("Bill Gates");
            int token3 = dynamicILInfo.GetTokenFor(typeof(Person).GetField("m_name").FieldHandle);
            int token4 = dynamicILInfo.GetTokenFor(typeof(Person).GetMethod("get_Age").MethodHandle);
            int token5 = dynamicILInfo.GetTokenFor(typeof(Person).GetMethod("set_Age").MethodHandle);
            int token6 = dynamicILInfo.GetTokenFor(typeof(Person).GetMethod("IncSalary").MethodHandle);

            PutInteger4(token0, 0x0002, code);
            PutInteger4(token1, 0x000e, code);
            PutInteger4(token2, 0x0015, code);
            PutInteger4(token3, 0x001a, code);
            PutInteger4(token4, 0x0021, code);
            PutInteger4(token5, 0x0028, code);
            PutInteger4(token6, 0x0034, code);
            dynamicILInfo.SetCode(code, 4);

            Person ret = (Person)dynamicMethod.Invoke(null, null);

            Assert.Equal(ret, Mock());
        }
示例#10
0
        public void ReturnType_Null()
        {
            DynamicMethod hello = new DynamicMethod("Hello",
                                                    null,
                                                    new Type[] { typeof(string) },
                                                    typeof(DynamicMethodTest).Module, true);

            Assert.AreEqual(typeof(void), hello.ReturnType, "#1");

            ILGenerator helloIL = hello.GetILGenerator();

            helloIL.Emit(OpCodes.Ret);

            DoNothing dn = (DoNothing)hello.CreateDelegate(typeof(DoNothing));

            dn("whatever");

            object[] invokeArgs = { "Hello, World!" };
            object   objRet     = hello.Invoke(null, invokeArgs);

            Assert.IsNull(objRet, "#2");
        }
        public void TestCalliGenerationIntInt()
        {
            int            callCount = 0;
            int            setVal    = 0;
            TakeReturn1Int vvct      = (i) =>
            {
                callCount++;
                setVal = i;
                return(i + 1);
            };
            var fp = Marshal.GetFunctionPointerForDelegate(vvct);
            CalliILGenerator generator = new CalliILGenerator();
            DynamicMethod    method    = new DynamicMethod("MyFunc", typeof(int), new Type[] { typeof(int) });

            generator.GenerateMethod(method.GetILGenerator(), method.ReturnType, new Type[] { typeof(int) }, fp);

            var ret = method.Invoke(null, new object[] { 5 });

            Assert.Equal(1, callCount);
            Assert.Equal(5, setVal);
            Assert.Equal(6, ret);
        }
示例#12
0
        /// <summary>
        /// Maps objects using IL emitting.
        /// </summary>
        /// <typeparam name="TSource"> Type of source object. </typeparam>
        /// <typeparam name="TDestination"> Type of destination object. </typeparam>
        /// <param name="sourceObject"> Source object. </param>
        /// <returns> Returns destination object. </returns>
        private TDestination MapUsingIL_Emitting <TSource, TDestination>(TSource sourceObject)
        {
            //dynamic method
            var dynamicMethod = new DynamicMethod("IL_Map", typeof(void),
                                                  new [] { typeof(TSource), typeof(TDestination) }, typeof(Mapper).Module);

            //getting IL generator
            var ilGen = dynamicMethod.GetILGenerator();

            //getting properties
            var properties = typeof(TSource).GetProperties();

            //creating destination object
            var destObject = Activator.CreateInstance <TDestination>();

            //constructing dynamic method
            foreach (var propertyInfo in properties)
            {
                //emitting arguments
                ilGen.Emit(OpCodes.Ldarg_1);
                ilGen.Emit(OpCodes.Ldarg_0);

                //getting destination object property
                var destProp = typeof(TDestination).GetProperty(propertyInfo.Name);

                //emitting calls
                ilGen.EmitCall(OpCodes.Callvirt, propertyInfo.GetGetMethod(), null);
                ilGen.EmitCall(OpCodes.Callvirt, destProp.GetSetMethod(), null);
            }

            //emitting return statement
            ilGen.Emit(OpCodes.Ret);

            //invoking dynamic method
            dynamicMethod.Invoke(null, new object [] { sourceObject, destObject });

            //returning destination object
            return(destObject);
        }
    private static object BaseCall(this object self, string methodName, Type returnType, object defaultReturn, object[] parameters)
    {
        var parameterTypes = parameters.Select(p => p.GetType()).ToArray();

        if (self.GetType().BaseType == null)
        {
            return(null);
        }
        var method = self.GetType().BaseType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parameterTypes, null);

        if (method == null || method.IsAbstract)
        {
            return(defaultReturn);
        }
        var dm = new DynamicMethod(methodName, returnType, new Type[] { self.GetType() }.Concat(parameterTypes).ToArray(), self.GetType());
        var il = dm.GetILGenerator();

        PushParameters(il, parameterTypes.Length);
        il.Emit(OpCodes.Call, method);
        il.Emit(OpCodes.Ret);
        return(dm.Invoke(null, new object[] { self }.Concat(parameters).ToArray()));
    }
示例#14
0
        public void CanEmitSerializerWithCustomDateFormat()
        {
            NullableDateTimeConverter converter = new NullableDateTimeConverter();
            DateTime?          date             = new DateTime(2019, 5, 4, 3, 2, 1);
            CsvColumnAttribute attribute        = new CsvColumnAttribute("Date")
            {
                DateFormat = "yyyy/MMM/dd H:mm:ss"
            };
            DynamicMethod serialize = new DynamicMethod("Serialize", typeof(string), new Type[] { typeof(DateTime?), typeof(IFormatProvider), typeof(char) }, typeof(DateTimeConverterTests));

            serialize.GetILGenerator()
            .DeclareLocal <DateTime?>(out LocalBuilder nullableLocal)
            .DeclareLocal <DateTime>(out LocalBuilder local)
            .Newobj <StringBuilder>()
            .Ldarg_0()
            .Emit(gen => converter.EmitAppendToStringBuilder(gen, nullableLocal, local, attribute))
            .Callvirt <StringBuilder>("ToString")
            .Ret();
            string serialized = (string)serialize.Invoke(null, new object?[] { date, CultureInfo.InvariantCulture, ',' }) !;

            serialized.Should().Be("2019/May/04 3:02:01");
        }
示例#15
0
        public T EvaluateExpression <T>()
        {
            var evaluator = new DynamicMethod("eval", typeof(T), new Type[] {});
            var ilGen     = evaluator.GetILGenerator();
            var parts     = _scheme.ParseInstructions();

            foreach (var part in parts)
            {
                if (part.Value == null)
                {
                    ilGen.Emit(part.Code);
                }
                else
                {
                    ilGen.Emit(part.Code, part.Value);
                }
            }

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

            return((T)evaluator.Invoke(null, new object[] {}));
        }
示例#16
0
        /// <summary>
        ///     Gets the pointer to the method table for the array type.
        /// </summary>
        /// <remarks>
        ///     The generated function is basically...
        ///     <code>
        ///     private static IntPtr GetMethodTablePointer_T(T[] array)
        ///     {
        ///         fixed(T* p = array)
        ///         {
        ///             return ((IntPtr*) p)[_methodTableOffset];
        ///         }
        ///     }
        /// </code>
        /// </remarks>
        private static IntPtr GetMethodTablePointer(Type baseType, Type arrayType, Type refType, object oneElemArray)
        {
            var mname  = "GetMethodTablePointer_" + baseType.Name;
            var method = new DynamicMethod(mname, typeof(IntPtr), new[] { arrayType }, MyModule);
            var il     = method.GetILGenerator();

            il.DeclareLocal(refType, true);
            il.Emit(OpCodes.Ldarg_0);                   // Load the array
            il.Emit(OpCodes.Ldc_I4_0);                  // Push a 0 offset
            il.Emit(OpCodes.Ldelema, baseType);         // Get address of array data
            il.Emit(OpCodes.Stloc_0);                   // Pin array
            il.Emit(OpCodes.Ldloc_0);                   // Load pinned (the store/load here is required for pinning)
            il.Emit(OpCodes.Conv_I);                    // Convert to IntPtr
            il.Emit(OpCodes.Ldc_I4, MethodTableOffset); // Load offset of method table pointer
            il.Emit(OpCodes.Conv_I);                    // Convert that to a ptrdiff_t
            il.Emit(OpCodes.Sizeof, typeof(IntPtr));    // Load sizeof(size_t)
            il.Emit(OpCodes.Mul);                       // Multiply offset * sizeof(size_t) to get offset in bytes
            il.Emit(OpCodes.Add);                       // Add that to the array data offset
            il.Emit(OpCodes.Ldind_I);                   // Get element at that address
            il.Emit(OpCodes.Ret);                       // Return it
            return((IntPtr)method.Invoke(null, new[] { oneElemArray }));
        }
示例#17
0
        //reflect+emit调用
        private void DynamicEmitInvoke <T>(Type eventType, Delegate ihandler, T message) where T : MessageBase
        {
            var handler       = ihandler.DynamicInvoke();
            var concreteType  = typeof(IProcessMessage <>).MakeGenericType(eventType);
            var dynamicMethod = new DynamicMethod(concreteType.Name + ihandler.GetType().Name, null, new Type[] { concreteType, typeof(T) });
            var method        = concreteType.GetMethod("ProcessMsg");
            //方法IL
            ILGenerator il = dynamicMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);              //put IProcessMessage<> arg into stack
            il.Emit(OpCodes.Ldarg_1);              //put T : MessageBase arg into stack
            if (eventType == method.DeclaringType) //call IProcessMessage.ProcessMsg
            {
                il.Emit(OpCodes.Call, method);
            }
            else
            {
                il.Emit(OpCodes.Callvirt, method);
            }
            il.Emit(OpCodes.Ret);                                                  //return
            dynamicMethod.Invoke(new object(), new object[] { handler, message }); //动态调用Delegate ihandler中的PROCESSMSG,参数是paras[0]
        }
示例#18
0
        private void GeneratePrefixForVoidDispatcherWorks()
        {
            // Generate prefix for SingleArg
            MethodInfo method     = AccessTools.Method(typeof(Foo), nameof(Foo.SingleArg));
            MethodInfo dispatcher = AccessTools.Method(
                typeof(MethodPatchFactory_Test),
                nameof(DispatcherVoid));
            MethodAccess  access = new MethodAccess(method);
            DynamicMethod prefix = MethodPatchFactory.GeneratePrefix(
                access,
                dispatcher,
                EPatchBehaviour.AlwaysCallOriginal);

            // Call
            object ret = prefix.Invoke(m_Foo, new object[] { m_Foo, 42 });

            Assert.IsType <bool>(ret);
            Assert.True((bool)ret);  // AlwaysCallOriginal
            Assert.Single(m_DispatcherCalls);
            Assert.NotNull(m_DispatcherCalls[0]);
            Assert.Same(access, m_DispatcherCalls[0]);
        }
示例#19
0
        public static bool performToolAction_Prefix(ref Tree __instance, Tool t, int explosion, Vector2 tileLocation, GameLocation location, ref bool __result)
        {
            // Gotta have the original method available for mattock stand-ins.
            if (performToolActionOriginal == null)
            {
                return(true);
            }

            // If the tool is a mattock and this object is one that requires a specific type of tool that is supported,
            // run the function with a stand-in tool instead.
            if (t is Mattock mattock && !mattock.struckFeatures.Contains(__instance))
            {
                // Treat the mattock as an axe for stumps.
                Axe standinAxe = mattock.asAxe();
                mattock.struckFeatures.Add(__instance);
                __result = (bool)performToolActionOriginal.Invoke(__instance, new object[] { __instance, standinAxe, explosion, tileLocation, location });
                return(false);
            }

            // Otherwise, just do the default functionality.
            return(true);
        }
示例#20
0
        static double ExecuteExpression(string expression, Dictionary <string, NumberType> variables, out IList <Token> lexics)
        {
            lexics = LexicalParser.Parse(expression).ToList();
            SyntaxTree    syntaxTree = SyntaxParser.Parse(lexics);
            DynamicMethod method     = ArithmeticTreeCompiler.Compile(syntaxTree);

            var undefinedVariables = syntaxTree.VariableNames.Except(variables.Keys).ToList();

            if (undefinedVariables.Count != 0)
            {
                throw new ArgumentException($"Undefined variables found: {string.Join(", ", undefinedVariables)}");
            }

            object[] args =
                syntaxTree.VariableNames
                .OrderBy(i => i)
                .Select(i => variables[i])
                .Cast <object>()
                .ToArray();

            return((double)method.Invoke(null, args));
        }
示例#21
0
        public override EmulationResult Emulate(Context ctx)
        {
            if (!(ctx.Instruction.Operand is IType iType))
            {
                throw new InvalidILException(ctx.Instruction.ToString());
            }

            var type = ctx.Emulator.DynamicContext.LookupMember <Type>(iType.MDToken.ToInt32());

            if (!_typeSizeCache.TryGetValue(type, out int size))
            {
                var dynamicMethod = new DynamicMethod(string.Empty, typeof(int), Type.EmptyTypes);
                var ilGenerator   = dynamicMethod.GetILGenerator();
                ilGenerator.Emit(SRE.OpCodes.Sizeof, type);
                ilGenerator.Emit(SRE.OpCodes.Ret);
                size = (int)dynamicMethod.Invoke(null, new object[0]);
                _typeSizeCache.Add(type, size);
            }

            ctx.Stack.Push(new I4Value(size));
            return(new NormalResult());
        }
        private Dictionary <string, object> GetExceptionFieldValues(Exception value)
        {
            // Obtain the unoverrided version of Message
            Type         exceptionType   = Globals.TypeOfException;
            PropertyInfo messageProperty = exceptionType.GetProperty("Message");
            MethodInfo   messageGetter   = messageProperty.GetMethod;

#if !NET_NATIVE
            DynamicMethod baseMessageImpl = new DynamicMethod("NonVirtual_Message", typeof(string), new Type[] { Globals.TypeOfException }, Globals.TypeOfException);

            ILGenerator gen = baseMessageImpl.GetILGenerator();
            gen.Emit(OpCodes.Ldarg, messageGetter.GetParameters().Length);
            gen.EmitCall(OpCodes.Call, messageGetter, null);
            gen.Emit(OpCodes.Ret);

            string messageValue = (string)baseMessageImpl.Invoke(null, new object[] { value });
#else
            string messageValue = string.Empty;
#endif

            // Populate the values for the necessary System.Exception private fields.
            Dictionary <string, object> fieldToValueDictionary = new Dictionary <string, object>();

            fieldToValueDictionary.Add("_className", value.GetType().ToString());
            fieldToValueDictionary.Add("_message", messageValue); //Thick framework retrieves the System.Exception implementation of message
            fieldToValueDictionary.Add("_data", value.Data);
            fieldToValueDictionary.Add("_innerException", value.InnerException);
            fieldToValueDictionary.Add("_helpURL", value.HelpLink);
            fieldToValueDictionary.Add("_stackTraceString", value.StackTrace);
            fieldToValueDictionary.Add("_remoteStackTraceString", null);
            fieldToValueDictionary.Add("_remoteStackIndex", 0);
            fieldToValueDictionary.Add("_exceptionMethodString", null);
            fieldToValueDictionary.Add("_HResult", value.HResult);
            fieldToValueDictionary.Add("_source", null); //value.source caused transparency error on build.
            fieldToValueDictionary.Add("_watsonBuckets", null);

            return(fieldToValueDictionary);
        }
示例#23
0
        public void While()
        {
            DynamicMethod   method    = new DynamicMethod("temp", typeof(int), Type.EmptyTypes);
            MethodGenerator g         = new MethodGenerator(method);
            const int       maxNumber = 15;
            var             num       = g.Declare(0);
            var             max       = g.Declare(maxNumber);

            g.While(() =>
            {
                g.Load(num);
                g.Load(max);
                return(LogicOperator.LessThan);
            }, () =>
            {
                g.Increment(num);
            });
            g.Load(num);
            g.Return();
            int result = (int)method.Invoke(null, new object[] { });

            Assert.AreEqual(maxNumber, result);
        }
示例#24
0
        private Func <object, object, object> GenerateOpMethod(OpCode op, Type returnType)
        {
            var method = new DynamicMethod(Guid.NewGuid().ToString(), returnType, new[] { Type, Type });

            var gen = method.GetILGenerator();

            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Ldarg_1);
            gen.Emit(op);
            gen.Emit(OpCodes.Ret);

            return((o0, o1) =>
            {
                try
                {
                    return method.Invoke(null, new[] { o0, o1 });
                }
                catch (TargetInvocationException ex)
                {
                    throw ex.InnerException;
                }
            });
        }
示例#25
0
        public void TestDynamicMethodEmitCalliNonBlittable()
        {
            string input = "Test string!", result = "!gnirts tseT";

            Type returnType = typeof(string);

            var dynamicMethod = new DynamicMethod("F", returnType, new Type[] { typeof(IntPtr), typeof(string) });

            ILGenerator il = dynamicMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_0);
            il.EmitCalli(OpCodes.Calli, CallingConvention.Cdecl, returnType, new Type[] { typeof(string) });
            il.Emit(OpCodes.Ret);

            IntPtr funcPtr = Marshal.GetFunctionPointerForDelegate(new StringReverseCdecl(StringReverse));

            object resultValue = dynamicMethod
                                 .Invoke(null, new object[] { funcPtr, input });

            Assert.IsType(returnType, resultValue);
            Assert.Equal(result, resultValue);
        }
示例#26
0
        static void IlGenerator()
        {
            var myMethod = new DynamicMethod("DividerMethod",
                                             typeof(double),
                                             new[] { typeof(int), typeof(int) },
                                             typeof(Program).Module);

            var il = myMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Div);   // 2 pop and one push from/into the evaluation stack
            il.Emit(OpCodes.Ret);

            var result = myMethod.Invoke(null, new object[] { 10, 2 });

            Console.WriteLine(result);

            var method  = (DivideDelegate)myMethod.CreateDelegate(typeof(DivideDelegate));
            var result2 = method(6, 2);

            Console.WriteLine(result2);
        }
示例#27
0
        private static void SetValue <TObject>(ref TObject o, FieldInfo field, object value)
        {
            Debug.Assert(o != null);
            Debug.Assert(value != null);
            Debug.Assert(field != null);
            Debug.Assert(field.FieldType == value.GetType());
            Debug.Assert(field.DeclaringType == typeof(TObject));

            var method = new DynamicMethod("", returnType: typeof(object),
                                           parameterTypes: new[] { typeof(object), typeof(object) },
                                           owner: field.DeclaringType);
            var generator = method.GetILGenerator();

            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Dup);
            generator.Emit(field.DeclaringType.IsValueType ? OpCodes.Unbox : OpCodes.Castclass, field.DeclaringType);
            generator.Emit(OpCodes.Ldarg_1);
            generator.Emit(OpCodes.Unbox_Any, field.FieldType);
            generator.Emit(OpCodes.Stfld, field);
            generator.Emit(OpCodes.Ret);

            o = (TObject)method.Invoke(o, new[] { o, value });
        }
示例#28
0
        public void TestDynamicMethodEmitCalliBlittable()
        {
            int a = 1, b = 1, result = 2;

            Type returnType = typeof(int);

            var dynamicMethod = new DynamicMethod("F", returnType, new Type[] { typeof(IntPtr), typeof(int), typeof(int) });

            ILGenerator il = dynamicMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Ldarg_0);
            il.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, returnType, new Type[] { typeof(int), typeof(int) });
            il.Emit(OpCodes.Ret);

            IntPtr funcPtr = Marshal.GetFunctionPointerForDelegate(new Int32SumStdCall(Int32Sum));

            object resultValue = dynamicMethod
                                 .Invoke(null, new object[] { funcPtr, a, b });

            Assert.IsType(returnType, resultValue);
            Assert.Equal(result, resultValue);
        }
示例#29
0
        public void Execute()
        {
            ConsoleTester.ClearAndStartCapturing();

            DynamicMethodGen dmg = DynamicMethodGen.Static(typeof(DynamicMethodTest)).Method(typeof(string), new TypeMapper())
                                   .Parameter(typeof(string), "name")
                                   .Parameter(typeof(string), "other");
            CodeGen g = dmg.GetCode();
            {
                g.Try();
                {
                    var name = g.Local(typeof(string), g.Arg("name"));
                    g.WriteLine("Hello " + name + "!");
                }
                g.CatchAll();
                {
                    g.WriteLine("Error");
                }
                g.End();
                g.Return(dmg.StaticFactory.Invoke(typeof(DynamicMethodTest), nameof(CallMe), g.Arg("other"), 2));
            }
            DynamicMethod dm = dmg.GetCompletedDynamicMethod(true);


            // reflection-style invocation
            Assert.That(dm.Invoke(null, new object[] { "Dynamic Method", "first1" }), Is.EqualTo("test240"));

            // delegate invocation
            Func <string, string, string> hello = (Func <string, string, string>)dm.CreateDelegate(typeof(Func <string, string, string>));

            Assert.That(hello("Delegate", "first1"), Is.EqualTo("test240"));

            ConsoleTester.AssertAndClear(@"Hello Dynamic Method!
Hello Delegate!
");
        }
示例#30
0
    public static int Main()
    {
        DynamicMethod method_builder = new DynamicMethod("ThrowException", typeof(void), new Type[0], typeof(Driver));
        ILGenerator   ilg            = method_builder.GetILGenerator();


        ilg.Emit(OpCodes.Newobj, typeof(MyException).GetConstructor(new Type[0]));
        ilg.Emit(OpCodes.Throw);

        try
        {
            method_builder.Invoke(null, null);
            return(2);
        }
        catch (TargetInvocationException tie)
        {
            if (!(tie.InnerException is MyException))
            {
                return(3);
            }
        }

        return(0);
    }
示例#31
0
        public static T2 MyMapTo <T2>(this object t)
        {
            if (t == null)
            {
                return(default(T2));
            }
            var type = t.GetType();

            var key = type.GetHashCode() ^ typeof(T2).GetHashCode();

            if (methodInfo == null)
            {
                DynamicMethod dynamicMethod = new DynamicMethod($"__{key}", typeof(T2), new[] { type });
                var           generator     = dynamicMethod.GetILGenerator();
                generator.Emit(OpCodes.Ldarg_0);
                var method = AllMethods["map-single"].MakeGenericMethod(type, typeof(T2));
                generator.Emit(OpCodes.Call, method);

                generator.Emit(OpCodes.Ret);
                methodInfo = dynamicMethod;
            }

            return((T2)methodInfo.Invoke(null, new object[] { t }));
        }
示例#32
0
        public static void Invoker()
        {
            var info = Assembly.GetExecutingAssembly().GetType("Chapter19.Fanshe").GetMethod("Invoker");


            //typeof(int).GetTypeInfo().DeclaredMethods

            //var types = typeof(Console).Attributes;
            //var ms = MethodInfo.GetCurrentMethod().Attributes;
            //Console.WriteLine(types + "\r\n" + ms);
            //ResolveEventHandler handler = (object sender, ResolveEventArgs args) => Assembly.ReflectionOnlyLoad(args.Name);
            //AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += handler;
            //AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve -= handler;

            //Attribute.GetCustomAttributes()
            {
                //var dyMothod = new DynamicMethod("Foo", null, null, typeof(Fanshe));
                //ILGenerator gen = dyMothod.GetILGenerator();
                //gen.EmitWriteLine("Hello world");
                //gen.Emit(OpCodes.Ret);
                //dyMothod.Invoke(null, null);

                //int x = 2;
                //int y = 3;
                //x *= y;
                //Console.WriteLine(x);
                var         dymethod = new DynamicMethod("TEST", null, null, typeof(void));
                ILGenerator gen      = dymethod.GetILGenerator();

                LocalBuilder localX = gen.DeclareLocal(typeof(int));
                LocalBuilder localY = gen.DeclareLocal(typeof(int));

                gen.Emit(OpCodes.Ldc_I4, 2);
                gen.Emit(OpCodes.Stloc, localX);
                gen.Emit(OpCodes.Ldc_I4, 3);
                gen.Emit(OpCodes.Stloc, localY);

                gen.Emit(OpCodes.Ldloc, localX);
                gen.Emit(OpCodes.Localloc, localY);
                gen.Emit(OpCodes.Mul);
                gen.Emit(OpCodes.Stloc, localX);
                gen.EmitWriteLine(localX);
                gen.Emit(OpCodes.Ret);

                //dymethod.Invoke(null, null);
            }
            {
                //int x = 5;

                //while (x<=10)
                //{
                //    Console.WriteLine(x++);
                //}
                //动态生成代码
                var dymethod = new DynamicMethod("Foo", null, null, typeof(void));
                var gen      = dymethod.GetILGenerator();

                //设置分支目标
                Label startLoop = gen.DefineLabel();
                Label endLoop   = gen.DefineLabel();

                //声明本地变量x
                LocalBuilder x = gen.DeclareLocal(typeof(int));
                //将参数推入评估栈
                gen.Emit(OpCodes.Ldc_I4, 5);
                //相当于 int x=5
                gen.Emit(OpCodes.Stloc, x);
                //标记标签位置  {
                gen.MarkLabel(startLoop);

                gen.Emit(OpCodes.Ldc_I4, 10);
                gen.Emit(OpCodes.Ldloc, x);
                // 如果第一个值小于第二个值就分支  if(x>10)
                //如果 x>10 结束标签,循环结束
                gen.Emit(OpCodes.Blt, endLoop);
                //Console.WriteLine(x);
                gen.EmitWriteLine(x);
                //++x;
                gen.Emit(OpCodes.Ldloc, x);
                gen.Emit(OpCodes.Ldc_I4, 1);
                gen.Emit(OpCodes.Add);
                gen.Emit(OpCodes.Stloc, x);

                gen.Emit(OpCodes.Br, startLoop);
                gen.MarkLabel(endLoop);
                gen.Emit(OpCodes.Ret);

                dymethod.Invoke(null, null);
            }
        }
 public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) =>
 m_owner.Invoke(obj, invokeAttr, binder, parameters, culture);
 public override int GetHashCode()
 {
     return(num + (int)GRANDPARENT_GET_HASH_CODE.Invoke(null, new object[] { this }));
 }
示例#35
0
文件: Program.cs 项目: sbluen/sample
    public static void Main()
    {
        // Create an array that specifies the types of the parameters
        // of the dynamic method. This dynamic method has a String
        // parameter and an Integer parameter.
        Type[] helloArgs = {typeof(string), typeof(int), typeof(int)};

        // Create a dynamic method with the name "Hello", a return type
        // of Integer, and two parameters whose types are specified by
        // the array helloArgs. Create the method in the module that
        // defines the String class.
        DynamicMethod hello = new DynamicMethod("Hello",
            typeof(int),
            helloArgs,
            typeof(string).Module);

        // Create an array that specifies the parameter types of the
        // overload of Console.WriteLine to be used in Hello.
        Type[] writeStringArgs = {typeof(string)};
        // Get the overload of Console.WriteLine that has one
        // String parameter.
        MethodInfo writeString = typeof(Console).GetMethod("WriteLine",
            writeStringArgs);

        // Get an ILGenerator and emit a body for the dynamic method,
        // using a stream size larger than the IL that will be
        // emitted.
        ILGenerator il = hello.GetILGenerator(256);
        // Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0);
        // Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, null);
        // The Hello method returns the value of the second argument;
        // to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ldc_I4_X, 1337);
        il.Emit(OpCodes.Add);
        il.Emit(OpCodes.Ret);

        // Add parameter information to the dynamic method. (This is not
        // necessary, but can be useful for debugging.) For each parameter,
        // identified by position, supply the parameter attributes and a
        // parameter name.
        hello.DefineParameter(1, ParameterAttributes.In, "message");
        hello.DefineParameter(2, ParameterAttributes.In, "valueToReturn");

        // Create a delegate that represents the dynamic method. This
        // action completes the method. Any further attempts to
        // change the method are ignored.
        HelloDelegate hi =
            (HelloDelegate) hello.CreateDelegate(typeof(HelloDelegate));

        // Use the delegate to execute the dynamic method.
        Console.WriteLine("\r\nUse the delegate to execute the dynamic method:");
        int retval = hi("\r\nHello, World!", 42, 30);
        Console.WriteLine("Invoking delegate hi(\"Hello, World!\", 42, 30) returned: " + retval);

        // Execute it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280, 37);
        Console.WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280, 37) returned: " + retval);

        Console.WriteLine("\r\nUse the Invoke method to execute the dynamic method:");
        // Create an array of arguments to use with the Invoke method.
        object[] invokeArgs = {"\r\nHello, World!", 42, 30};
        // Invoke the dynamic method using the arguments. This is much
        // slower than using the delegate, because you must create an
        // array to contain the arguments, and value-type arguments
        // must be boxed.
        object objRet = hello.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new CultureInfo("en-us"));
        Console.WriteLine("hello.Invoke returned: " + objRet);

        Console.WriteLine("\r\n ----- Display information about the dynamic method -----");
        // Display MethodAttributes for the dynamic method, set when
        // the dynamic method was created.
        Console.WriteLine("\r\nMethod Attributes: {0}", hello.Attributes);

        // Display the calling convention of the dynamic method, set when the
        // dynamic method was created.
        Console.WriteLine("\r\nCalling convention: {0}", hello.CallingConvention);

        // Display the declaring type, which is always null for dynamic
        // methods.
        if (hello.DeclaringType == null)
        {
            Console.WriteLine("\r\nDeclaringType is always null for dynamic methods.");
        }
        else
        {
            Console.WriteLine("DeclaringType: {0}", hello.DeclaringType);
        }

        // Display the default value for InitLocals.
        if (hello.InitLocals)
        {
            Console.Write("\r\nThis method contains verifiable code.");
        }
        else
        {
            Console.Write("\r\nThis method contains unverifiable code.");
        }
        Console.WriteLine(" (InitLocals = {0})", hello.InitLocals);

        // Display the module specified when the dynamic method was created.
        Console.WriteLine("\r\nModule: {0}", hello.Module);

        // Display the name specified when the dynamic method was created.
        // Note that the name can be blank.
        Console.WriteLine("\r\nName: {0}", hello.Name);

        // For dynamic methods, the reflected type is always null.
        if (hello.ReflectedType == null)
        {
            Console.WriteLine("\r\nReflectedType is null.");
        }
        else
        {
            Console.WriteLine("\r\nReflectedType: {0}", hello.ReflectedType);
        }

        //beyond scope of project
        //		if (hello.ReturnParameter == null)
        //		{
        //			Console.WriteLine("\r\nMethod has no return parameter.");
        //		}
        //		else
        //		{
        //			Console.WriteLine("\r\nReturn parameter: {0}", hello.ReturnParameter);
        //		}

        // If the method has no return type, ReturnType is System.Void.
        Console.WriteLine("\r\nReturn type: {0}", hello.ReturnType);

        // ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
        // that can be used to enumerate the custom attributes of the
        // return value. At present, there is no way to set such custom
        // attributes, so the list is empty.
        //beyond scope of project
        //		if (hello.ReturnType == typeof(void))
        //		{
        //			Console.WriteLine("The method has no return type.");
        //		}
        //		else
        //		{
        //			ICustomAttributeProvider caProvider = hello.ReturnTypeCustomAttributes;
        //			object[] returnAttributes = caProvider.GetCustomAttributes(true);
        //			if (returnAttributes.Length == 0)
        //			{
        //				Console.WriteLine("\r\nThe return type has no custom attributes.");
        //			}
        //			else
        //			{
        //				Console.WriteLine("\r\nThe return type has the following custom attributes:");
        //				foreach( object attr in returnAttributes )
        //				{
        //					Console.WriteLine("\t{0}", attr.ToString());
        //				}
        //			}
        //		}

        Console.WriteLine("\r\nToString: {0}", hello.ToString());
        Console.WriteLine("\r\nToString: {0}", hello.ToString());

        // Display parameter information.
        ParameterInfo[] parameters = hello.GetParameters();
        Console.WriteLine("\r\nParameters: name, type, ParameterAttributes");
        foreach( ParameterInfo p in parameters )
        {
            Console.WriteLine("\t{0}, {1}, {2}",
                p.Name, p.ParameterType, p.Attributes);
        }
        Console.WriteLine("array assignment");
        Type[] paramTypes = { typeof(uint), typeof(string), typeof(string), typeof(uint) };
        Console.WriteLine(paramTypes[1]);
    }
示例#36
0
    public static void Main()
    {
        // Create an array that specifies the types of the parameters
        // of the dynamic method. This method has a string parameter
        // and an int parameter.
        Type[] helloArgs = { typeof(string), typeof(int) };

        // Create a dynamic method with the name "Hello", a return type
        // of int, and two parameters whose types are specified by the
        // array helloArgs. Create the method in the module that
        // defines the Test class.
        DynamicMethod hello = new DynamicMethod("Hello",
                                                typeof(int),
                                                helloArgs,
                                                typeof(Test).Module);

        // <Snippet2>
        // Create an array that specifies the parameter types of the
        // overload of Console.WriteLine to be used in Hello.
        Type[] writeStringArgs = { typeof(string) };
        // Get the overload of Console.WriteLine that has one
        // String parameter.
        MethodInfo writeString =
            typeof(Console).GetMethod("WriteLine", writeStringArgs);

        // Get an ILGenerator and emit a body for the dynamic method.
        ILGenerator il = hello.GetILGenerator();

        // Load the first argument, which is a string, onto the stack.
        il.Emit(OpCodes.Ldarg_0);
        // Call the overload of Console.WriteLine that prints a string.
        il.EmitCall(OpCodes.Call, writeString, null);
        // The Hello method returns the value of the second argument;
        // to do this, load the onto the stack and return.
        il.Emit(OpCodes.Ldarg_1);
        il.Emit(OpCodes.Ret);
        // </Snippet2>

        // <Snippet3>
        // Create a delegate that represents the dynamic method. This
        // action completes the method, and any further attempts to
        // change the method will cause an exception.
        HelloInvoker hi =
            (HelloInvoker)hello.CreateDelegate(typeof(HelloInvoker));
        // </Snippet3>

        // Use the delegate to execute the dynamic method. Save and
        // print the return value.
        int retval = hi("\r\nHello, World!", 42);

        Console.WriteLine("Executing delegate hi(\"Hello, World!\", 42) returned {0}",
                          retval);

        // Do it again, with different arguments.
        retval = hi("\r\nHi, Mom!", 5280);
        Console.WriteLine("Executing delegate hi(\"Hi, Mom!\", 5280) returned {0}",
                          retval);

        // <Snippet4>
        // Create an array of arguments to use with the Invoke method.
        object[] invokeArgs = { "\r\nHello, World!", 42 };
        // Invoke the dynamic method using the arguments. This is much
        // slower than using the delegate, because you must create an
        // array to contain the arguments, and ValueType arguments
        // must be boxed.
        object objRet = hello.Invoke(null, invokeArgs);

        Console.WriteLine("hello.Invoke returned {0}", objRet);
        // </Snippet4>
    }