Beispiel #1
0
        static void Main(string[] args)
        {
            var division = new DynamicMethod(
                    "Division",
                    typeof(double),  // Return type
                    new[] {
                        typeof(int), // Parameter: a
                        typeof(int)  // Parameter: b
                    },
                    typeof(Program).Module
                );

            ILGenerator il = division.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Div);
            il.Emit(OpCodes.Ret);

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

            Console.WriteLine(result);
            var divideIt =
                (DivideInvoker)division.CreateDelegate(typeof(DivideInvoker));

            var divideItResult = divideIt(4, 0);

            Console.WriteLine(divideItResult);
        }
Beispiel #2
0
        /// <summary>
        /// the address of a field relative to the address an object reference of that type points to.  this function is very expensive to call.
        /// </summary>
        /// <param name="field"></param>
        /// <returns></returns>
        public static IntPtr GetManagedOffset(this FieldInfo field)
        {
            Type type = field.DeclaringType;

            var dyn = new System.Reflection.Emit.DynamicMethod(
                "xxz0", typeof(IntPtr), new Type[] { typeof(object) }, typeof(ReflectionExtensions).Module, true);
            var il = dyn.GetILGenerator();

            var pin      = il.DeclareLocal(type, true);
            var baseaddr = il.DeclareLocal(typeof(IntPtr));

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Stloc, pin);         // force cast object to type (invalid), and pin

            il.Emit(OpCodes.Ldloc, pin);         // base address of reference (points to typeinfo)
            il.Emit(OpCodes.Conv_I);             // convert object ref to intptr (invalid)
            il.Emit(OpCodes.Stloc, baseaddr);

            il.Emit(OpCodes.Ldloc, pin);
            il.Emit(OpCodes.Ldflda, field);      // address of desired field
            il.Emit(OpCodes.Conv_I);             // convert field& to intptr (invalid)
            il.Emit(OpCodes.Ldloc, baseaddr);
            il.Emit(OpCodes.Sub);
            il.Emit(OpCodes.Ret);

            return((IntPtr)dyn.Invoke(null, new object[] { new object() }));
        }
Beispiel #3
0
		public void TestCall2()
		{
			var parameters = new[] { typeof(int), typeof(int) };

			var dm = new DynamicMethod("soma", typeof(int), parameters);

			var gen = dm.GetILGenerator();

			gen.DeclareLocal (typeof(Math));
			var ctor = typeof(Math).GetConstructors () [0];

			gen.Emit (OpCodes.Newobj, ctor);
			gen.Emit (OpCodes.Stloc, 0);
            gen.Emit (OpCodes.Ldobj, 0);

			//gen.Emit(OpCodes.Ldarg_0);
			//gen.Emit(OpCodes.Ldarg_1);
			//var soma = GetType ().GetMethod ("Soma");

			//gen.EmitCall (OpCodes.Callvirt, soma, new Type[] {  });

			gen.Emit (OpCodes.Ldc_I4, 2);

			gen.Emit(OpCodes.Ret);

			var result = dm.Invoke(null, new object[] { 1, 1 });

			//var func = (Func<int, int, int>)dm.CreateDelegate(typeof(Func<int, int, int>));

			Assert.AreEqual (2, result);
		}          
        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);

            ModuleBuilder moduleBuilder= assemblyBuilder.DefineDynamicModule("DynamicModule", "DynamicAssembly.dll");
            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");
        }
Beispiel #5
0
        /// <summary>
        /// need to invoke a base class method that is over ridden by the subclass?
        /// no fear use this extension shamelessly taken from http://www.simplygoodcode.com/2012/08/invoke-base-method-using-reflection.html
        /// 
        /// </summary>
        /// <param name="methodInfo"></param>
        /// <param name="targetObject"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public static object InvokeNotOverride(this MethodInfo methodInfo, object targetObject, params object[] arguments)
        {
            var parameters = methodInfo.GetParameters();

            if (parameters.Length == 0)
            {
                if (arguments != null && arguments.Length != 0)
                    throw new Exception("Arguments cont doesn't match");
            }
            else
            {
                if (parameters.Length != arguments.Length)
                    throw new Exception("Arguments cont doesn't match");
            }

            Type returnType = null;
            if (methodInfo.ReturnType != typeof(void))
            {
                returnType = methodInfo.ReturnType;
            }

            var type = targetObject.GetType();
            var dynamicMethod = new DynamicMethod("", returnType,
                    new Type[] { type, typeof(Object) }, type);

            var iLGenerator = dynamicMethod.GetILGenerator();
            iLGenerator.Emit(OpCodes.Ldarg_0); // this

            for (var i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];

                iLGenerator.Emit(OpCodes.Ldarg_1); // load array argument

                // get element at index
                iLGenerator.Emit(OpCodes.Ldc_I4_S, i); // specify index
                iLGenerator.Emit(OpCodes.Ldelem_Ref); // get element

                var parameterType = parameter.ParameterType;
                if (parameterType.IsPrimitive)
                {
                    iLGenerator.Emit(OpCodes.Unbox_Any, parameterType);
                }
                else if (parameterType == typeof(object))
                {
                    // do nothing
                }
                else
                {
                    iLGenerator.Emit(OpCodes.Castclass, parameterType);
                }
            }

            iLGenerator.Emit(OpCodes.Call, methodInfo);
            iLGenerator.Emit(OpCodes.Ret);

            return dynamicMethod.Invoke(null, new object[] { targetObject, arguments });
        }
Beispiel #6
0
	public void GetTokenFor_String () {
		DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(string), Type.EmptyTypes, typeof(DynamicILInfoTest), false);
		DynamicILInfo il = dm.GetDynamicILInfo();
 
		byte[] code = { 0x00, 0x72, 0x01, 0x00, 0x00, 0x70, 0x2a };
		int token0 = il.GetTokenFor("ABCD");
		PutInteger4(token0, 0x0002, code);
		il.SetCode(code, 8);
 
		var res = dm.Invoke(null, null);
		Assert.AreEqual ("ABCD", res);
	}
		/// <summary>
		/// Creates a new 2D array instance of ITile using the default Terraria.Tile implementation.
		/// 
		/// This cannot be compiled in the OTAPI solution as the Terraria.Tile will not implement 
		/// ITile at compile time.
		/// </summary>
		/// <returns>A 2D ITile array instance</returns>
		private static ITile[,] GetNewTileCollection()
		{
			var dm = new DynamicMethod("GetNewTileCollection", typeof(ITile[,]), null);
			var processor = dm.GetILGenerator();

			processor.Emit(OpCodes.Ldsfld, typeof(global::Terraria.Main).GetField("maxTilesX"));
			processor.Emit(OpCodes.Ldsfld, typeof(global::Terraria.Main).GetField("maxTilesY"));
			processor.Emit(OpCodes.Newobj, typeof(global::Terraria.Tile[,]).GetConstructors().Single(x => x.GetParameters().Length == 2));
			processor.Emit(OpCodes.Ret);

			return (ITile[,])dm.Invoke(null, null);
		}
        public static void Main(string[] args)
        {
            DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(void),
                                                 new Type[] { }, typeof(HelloWorldLCG), false);

            ILGenerator il = dm.GetILGenerator();
            il.Emit(OpCodes.Ldstr, "hello, world");
            il.Emit(OpCodes.Call, typeof(Console).GetMethod("WriteLine",
                    new Type[] { typeof(string) }));
            il.Emit(OpCodes.Ret);

            dm.Invoke(null, null);
        }
Beispiel #9
0
	public void GetTokenFor_Type () {
		DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(Type), Type.EmptyTypes, typeof(DynamicILInfoTest), false);
		DynamicILInfo il = dm.GetDynamicILInfo();

		byte[] code = { 0x00, 0xd0, 0x01, 0x00, 0x00, 0x70, 0x28, 0x04, 0x00, 0x00, 0x0a, 0x00, 0x2a };
		int token0 = il.GetTokenFor(typeof (int).TypeHandle);
		int token1 = il.GetTokenFor(typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }).MethodHandle);
		PutInteger4(token0, 0x0002, code);
		PutInteger4(token1, 0x0007, code);
		il.SetCode(code, 8);
 
		var res = dm.Invoke(null, null);
		Assert.AreEqual (typeof (int), res);
	}
Beispiel #10
0
	public void GetTokenFor_Method () {
		DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(string), Type.EmptyTypes, typeof(DynamicILInfoTest), false);
		DynamicILInfo il = dm.GetDynamicILInfo();

		// ldstr "ABCD"; call string::ToLower (); ret
		byte[] code = { 0x00, 0x72, 0x01, 0x00, 0x00, 0x70, 0x28, 0x04, 0x00, 0x00, 0x0a, 0x00, 0x2a };
		int token0 = il.GetTokenFor("ABCD");
		int token1 = il.GetTokenFor(typeof(string).GetMethod("ToLower", Type.EmptyTypes).MethodHandle);
		PutInteger4(token0, 0x0002, code);
		PutInteger4(token1, 0x0007, code);
		il.SetCode(code, 8);
 
		var res = dm.Invoke(null, null);
		Assert.AreEqual ("abcd", res);
	}
Beispiel #11
0
        public void Do()
        {
            var parameters = new[] { typeof(int), typeof(int) };

            var dm = new DynamicMethod("soma", typeof(int), parameters);

            var gen = dm.GetILGenerator();

            gen.Emit(OpCodes.Ldc_I4, 1);
            gen.Emit(OpCodes.Ldc_I4, 1);
            gen.Emit(OpCodes.Add);
            gen.Emit(OpCodes.Ret);

            var result = dm.Invoke(null, new object[] { 1, 1 });

            Assert.AreEqual(2, result);
        }   
Beispiel #12
0
        public void TwoPlusTwoWithParameters_Reference()
        {
            // arrange
            var dm = new DynamicMethod("SomeName", typeof(int), new[] { typeof(int), typeof(int) });

            var ilgen = dm.GetILGenerator();
            ilgen.Emit(OpCodes.Ldarg_0);
            ilgen.Emit(OpCodes.Ldarg_1);
            ilgen.Emit(OpCodes.Add);
            ilgen.Emit(OpCodes.Ret);

            // act
            var result = dm.Invoke(null, new object[] { 2, 2 });

            // assert
            result.Should().Be(4);
        }
        public void DeclareLocal_EmitsProvidedInstructions(byte value)
        {
            var method = new DynamicMethod("Test", typeof(byte), new Type[0]);
            var generator = method.GetILGenerator();

            var subject = new ILGeneratorWrapper(generator);

            // Act
            var local = subject.DeclareLocal(typeof(byte), false);
            subject.Emit(OpCodes.Ldc_I4_S, value);
            subject.Emit(OpCodes.Stloc, local);
            subject.Emit(OpCodes.Ldloc, local);
            subject.Emit(OpCodes.Ret);
            byte result = (byte)method.Invoke(null, new object[0]);

            // Assert
            Assert.AreEqual(value, result);
        }
        public void EmitBranch_EmitsProvidedInstructions(int value)
        {
            var method = new DynamicMethod("Test", typeof(int), new Type[0]);
            var generator = method.GetILGenerator();

            var subject = new ILGeneratorWrapper(generator);

            // Act
            var label = subject.DefineLabel();
            subject.Emit(OpCodes.Ldc_I4, value);
            subject.Emit(OpCodes.Br, label);
            subject.Emit(OpCodes.Ldc_I4, 123);
            subject.MarkLabel(label);
            subject.Emit(OpCodes.Ret);
            int result = (int)method.Invoke(null, new object[0]);

            // Assert
            Assert.AreEqual(value, result);
        }
        public void GenerateFilterIlTest()
        {
            // Arrange
            ExpressFormsFilterText target = new ExpressFormsFilterText();
            DynamicMethod method = new DynamicMethod("Wow", typeof(bool), new Type[] { typeof(TestClass2) });
            ILGenerator generator = method.GetILGenerator();
            PropertyInfo property = typeof(TestClass2).GetProperty("Text");
            Dictionary<string, string> thisFilter = new Dictionary<string, string>() { { "filterMode", Convert.ToString(TestContext.DataRow["FilterMode"]) }, { "filterText", Convert.ToString(TestContext.DataRow["FilterText"]) } };
            TestClass2 argument = new TestClass2() { Text = Convert.ToString(TestContext.DataRow["ValueToMatch"]) };

            // Act
            target.GenerateFilterIl(generator, thisFilter, property);
            // The method would eventually return true if it didn't encounter a reason to return false.
            generator.EmitReturnTrue();
            object objResult = method.Invoke(null, new[] { argument });
            bool result = (bool)objResult;

            // Assert
            bool expected = Convert.ToBoolean(TestContext.DataRow["Result"]);
            Assert.AreEqual(expected, result);
        }
Beispiel #16
0
        /// <summary>
        /// Rick Byers
        /// http://blogs.msdn.com/b/rmbyers/archive/2008/08/16/invoking-a-virtual-method-non-virtually.aspx
        /// </summary>
        public static object NonVirtualInvoke(object thisInstance, MethodInfo method,
            object[] args)
        {
            // Use LCG to generate a temporary method that uses a 'call' instruction to
            // invoke the supplied method non-virtually.
            // Doing a non-virtual call on a virtual method outside the class that
            // defines it will normally generate a VerificationException (PEVerify
            // says "The 'this' parameter to the call must be the callng method's
            // 'this' parameter.").  By associating the method with a type ("Program")
            // in a full-trust assembly, we tell the JIT to skip this verification step.
            // Alternately we might want to associate it with method.DeclaringType - the
            // verification might then pass even if it's not skipped (eg. partial trust).
            var paramTypes = new List<Type>();

            if (!method.IsStatic)
                paramTypes.Add(method.DeclaringType);
            paramTypes.AddRange(method.GetParameters().Select(p => p.ParameterType));
            DynamicMethod dm = new DynamicMethod(
                "NonVirtualInvoker",    // name
                method.ReturnType,      // same return type as method we're calling
                paramTypes.ToArray(),   // same parameter types as method we're calling
                method.DeclaringType); // associates with this full-trust code
            ILGenerator il = dm.GetILGenerator();
            for (int i = 0; i < paramTypes.Count; i++)
                il.Emit(OpCodes.Ldarg, i);             // load all args
            il.EmitCall(OpCodes.Call, method, null);   // call the method non-virtually
            il.Emit(OpCodes.Ret);                      // return what the call returned

            List<object> fullArgsList;
            if (args == null)
            {
                fullArgsList = new List<object>(1);
                fullArgsList.Add(thisInstance);
            }
            else
            {
                fullArgsList = new List<object>(args.Length + 1);
                fullArgsList.Add(thisInstance);
                fullArgsList.AddRange(args);
            }

            // Call the emitted method, which in turn will call the method requested
            return dm.Invoke(null, fullArgsList.ToArray());
        }
Beispiel #17
0
        static void DynamicCreateMethod()
        {
            // 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) };

            // 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.Ret);

            // 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);
            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.
            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());

            // 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.
            ParameterBuilder parameter1 = hello.DefineParameter(1,ParameterAttributes.In,"message");
            ParameterBuilder parameter2 = hello.DefineParameter(2,ParameterAttributes.In,"valueToReturn");

            // 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);
            }

            // 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.
            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);
            Console.WriteLine("Invoking delegate hi(\"Hello, World!\", 42) returned: " + retval);

            // Execute it again, with different arguments.
            retval = hi("\r\nHi, Mom!", 5280);
            Console.WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280) 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 };
            // 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 System.Globalization.CultureInfo("en-us"));
            Console.WriteLine("hello.Invoke returned: " + objRet);
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            //test();

            DynamicMethod dyn_m_1 = new DynamicMethod("T", typeof(int), new Type[] { typeof(uint) });

            ILGenerator il_1 = dyn_m_1.GetILGenerator();

            il_1.Emit(OpCodes.Break);
            il_1.Emit(OpCodes.Ldc_I4, 0xFFFFFFFF);
            //il_1.Emit (OpCodes.Ldc_I4,0xFFFFFFFF);
            //il_1.Emit (OpCodes.Ldc_I4,0xFFFFFFFF);
            //il_1.Emit (OpCodes.Ldc_I4,0xFFFFFFFF);
            il_1.Emit(OpCodes.Pop);
            il_1.Emit(OpCodes.Ldc_I4, 0xFFFFFFFF);
            il_1.Emit(OpCodes.Break);
            //il_1.Emit (OpCodes.Pop);
            //il_1.Emit (OpCodes.Pop);
            //il_2.Emit (OpCodes.Call, typeof(MainClass).GetMethod ("B", BindingFlags.Static | BindingFlags.Public));
            il_1.Emit(OpCodes.Ret);

            dyn_m_1.Invoke(null, new object[] { 0xFFFFFFFF });
            //DynamicMethod dm = new DynamicMethod("TEST", typeof(int), new Type[] { typeof(object) });
            //var generator = dm.GetILGenerator();

            //generator.Emit(OpCodes.Ldarg_0);
            //generator.Emit(OpCodes.Ldarg,0);
            //generator.Emit(OpCodes.Conv_I);
            //generator.Emit(OpCodes.Ldc_I4,8);
            //generator.Emit(OpCodes.Sub);
            //generator.Emit(OpCodes.Conv_I);
            //generator.Emit(OpCodes.Ret);

            //object c = new object();

            //int test = (int)dm.Invoke(null, new object[] { c });

            //**(int**)
            //Console.WriteLine(**(int**)test);

            //TypedReference tr = __makeref(c);
            //IntPtr intPtrAlternativeMethod = **(IntPtr**)(&tr);

            //Console.WriteLine ((int)&tr);

            Console.WriteLine(99999);

            /*
            testClass tc = new testClass();

            //Get the address.
            GCHandle objHandle = GCHandle.Alloc(tc, GCHandleType.WeakTrackResurrection);
            IntPtr intPtrAddressOfObjectPointer = GCHandle.ToIntPtr(objHandle);
            IntPtr intPtrObjectPtr = (IntPtr)Marshal.ReadInt32(intPtrAddressOfObjectPointer);

            //Alternative way of getting the same pointer to a pointer...
            TypedReference tr = __makeref(tc);
            IntPtr intPtrAlternativeMethod = **(IntPtr**)(&tr);

            Console.WriteLine("A) Address of object pointer: " + intPtrAddressOfObjectPointer);
            //Console.WriteLine("Bytes at address: " + getBytes(intPtrAddressOfObjectPointer));
            //Console.WriteLine("");
            Console.WriteLine("B) Address of actual object: " + intPtrObjectPtr);
            //Console.WriteLine("Ad(alt) of actual object: " + intPtrAlternativeMethod);

            testByVal(tc);
            testByRef(ref tc);

            MA();
            MB();
            */
            //Console.ReadKey();
        }
Beispiel #19
0
	public void GetTokenFor_FieldInfo () {
		aField = aField + 1;
		DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(RuntimeFieldHandle), Type.EmptyTypes, typeof(DynamicILInfoTest), false);
		DynamicILInfo il = dm.GetDynamicILInfo();

		var f = typeof (DynamicILInfoTest).GetField ("aField", BindingFlags.Static|BindingFlags.NonPublic).FieldHandle;
 
		byte[] code = { 0x00, 0xd0, 0x01, 0x00, 0x00, 0x70, 0x2a };
		int token0 = il.GetTokenFor(f);
		PutInteger4(token0, 0x0002, code);
		il.SetCode(code, 8);
 
		var res = dm.Invoke(null, null);
		Assert.AreEqual (f, res);
	}
Beispiel #20
0
	public void GetTokenFor_DynamicMethod () {
		DynamicMethod dm = new DynamicMethod("HelloWorld", typeof(RuntimeMethodHandle), Type.EmptyTypes, typeof(DynamicILInfoTest), false);
		DynamicILInfo il = dm.GetDynamicILInfo();
 
		byte[] code = { 0x00, 0xd0, 0x01, 0x00, 0x00, 0x70, 0x2a };
		int token0 = il.GetTokenFor(dm);
		PutInteger4(token0, 0x0002, code);
		il.SetCode(code, 8);
 
		var res = dm.Invoke(null, null);
		Assert.AreEqual (dm.MethodHandle, res);
	}
        public void EmitString_EmitsProvidedInstructions(string message)
        {
            var method = new DynamicMethod("Test", typeof(string), new Type[0]);
            var generator = method.GetILGenerator();

            var subject = new ILGeneratorWrapper(generator);

            // Act
            subject.Emit(OpCodes.Ldstr, message);
            subject.Emit(OpCodes.Ret);
            string result = (string)method.Invoke(null, new object[0]);

            // Assert
            Assert.AreEqual(message, result);
        }
        public void EmitSwitch_EmitsProvidedInstructions(int value)
        {
            var method = new DynamicMethod("Test", typeof(int), new Type[0]);
            var generator = method.GetILGenerator();

            var subject = new ILGeneratorWrapper(generator);

            // Act
            var endOfMethod = subject.DefineLabel();
            var labels = new[] { subject.DefineLabel(), subject.DefineLabel() };

            subject.Emit(OpCodes.Ldc_I4_0);
            subject.Emit(OpCodes.Switch, labels);
            subject.MarkLabel(labels[0]);
            subject.Emit(OpCodes.Ldc_I4, value);
            subject.Emit(OpCodes.Br_S, endOfMethod);
            subject.MarkLabel(labels[1]);
            subject.Emit(OpCodes.Ldc_I4_8, value);
            subject.Emit(OpCodes.Br_S, endOfMethod);
            subject.MarkLabel(endOfMethod);
            subject.Emit(OpCodes.Ret);

            int result = (int)method.Invoke(null, new object[0]);

            // Assert
            Assert.AreEqual(value, result);
        }
Beispiel #23
0
        public object QueryInterface(string name)
        {
            Guid iid = Guid.Empty;
            object o = null;
            if (COMUtilities.IsValidGUID(name))
            {
                iid = new Guid(name);
            }
            else
            {
                foreach (KeyValuePair<Guid, string> pair in Interfaces)
                {
                    if (String.Compare(pair.Value, name, true) == 0)
                    {
                        iid = pair.Key;
                        break;
                    }
                }
            }

            Type type = COMUtilities.GetInterfaceType(iid);
            if (type != null)
            {
                DynamicMethod method = new DynamicMethod("CastTypeInstance", type, new Type[] { typeof(object) });
                ILGenerator gen = method.GetILGenerator(256);
                gen.Emit(OpCodes.Ldarg_0);
                gen.Emit(OpCodes.Castclass, type);
                gen.Emit(OpCodes.Ret);
                o = method.Invoke(null, new object[] { Instance });
            }

            return o;
        }
        public void EmitFloat_EmitsProvidedInstructions(float value)
        {
            var method = new DynamicMethod("Test", typeof(float), new Type[0]);
            var generator = method.GetILGenerator();

            var subject = new ILGeneratorWrapper(generator);

            // Act
            subject.Emit(OpCodes.Ldc_R4, value);
            subject.Emit(OpCodes.Ret);
            float result = (float)method.Invoke(null, new object[0]);

            // Assert
            Assert.AreEqual(value, result);
        }
        public static int Execute(TreeNode root)
        {
            DynamicMethod method = new DynamicMethod("Exec_" + i++,
                                                     typeof(int),
                                                     new Type[] { },
                                                     typeof(Program).Module);

            ILGenerator generator = method.GetILGenerator();

            ILStack = new Stack<MathOpOrVal>();
            BuildStack(ILStack, root);

            while (ILStack.Count > 0)
            {
                MathOpOrVal mv = ILStack.Pop();
                if (mv.Op != null)
                {
                    switch (mv.Op)
                    {
                        case MathOp.Add:
                            Console.WriteLine("add");
                            generator.Emit(OpCodes.Add);
                            break;

                        case MathOp.Sub:
                            Console.WriteLine("sub");
                            generator.Emit(OpCodes.Sub);
                            break;

                        case MathOp.Mul:
                            Console.WriteLine("mul");
                            generator.Emit(OpCodes.Mul);
                            break;

                        case MathOp.Div:
                            Console.WriteLine("div");
                            generator.Emit(OpCodes.Div);
                            break;
                    }
                }
                else
                {
                    Console.WriteLine("ldc " + mv.Value.Value);
                    generator.Emit(OpCodes.Ldc_I4, mv.Value.Value);
                }
            }

            generator.Emit(OpCodes.Ret);

            return (int)method.Invoke(null,
                                      BindingFlags.ExactBinding,
                                      null,
                                      new object[] { },
                                      null);
        }
Beispiel #26
0
		public void TestCall()
		{
			var parameters = new[] { typeof(int), typeof(int) };

			var dm = new DynamicMethod("soma", typeof(int), parameters);

			var gen = dm.GetILGenerator();

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

			var soma = GetType ().GetMethod ("Soma");

			gen.Emit (OpCodes.Call, soma);

			gen.Emit(OpCodes.Ret);

			var result = dm.Invoke(null, new object[] { 1, 1 });

			Assert.AreEqual (2, result);
		}         
        private Dictionary<string, object> GetExceptionFieldValues(Exception value)
        {
            // Obtain the unoverridden 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;
        }
        static int ILDivider(int one, int two)
        {
            var divMethod = new DynamicMethod("DivideMethod", //name of method
                 typeof(int), //return type
                 new[] { typeof(int), typeof(int)},//parameters
                 typeof(Program).Module); //the module it lives in, remember these things called modules exist, even though you cannot make them in Visual Studio so nobody knows about them
            var il = divMethod.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);//take the first argument to the method and loads it to the top of the evaluation stack
            il.Emit(OpCodes.Ldarg_1);//load second argument to the top of eval stack
            il.Emit(OpCodes.Div);// this will remove the last 2 values on the stack and divide them and then put the result on top of the stack
            il.Emit(OpCodes.Ret);

            //first way to call dynamic method
            var result = divMethod.Invoke(
                //we are not invoking the method in the context of an instance of an object so it can be null, therefore you could not use "this" in the method
                null,
                //an array of the arguments you are sending into the method
                new object[] { one, two });

            //second way to call dynamic method
            var method = (DivideDelegate)divMethod.CreateDelegate(typeof(DivideDelegate));

            result = method(one, two);

            return (int) result;
        }