Esempio n. 1
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="method">需要写入IL流的<see cref="DynamicMethod"/>实例</param>
        public MSILWriter(DynamicMethod method)
        {
            var parameters = method.GetParameters();

            _methodHeader = new MethodHeader
            {
                Attributes     = method.CallingConvention,
                DeclaringType  = method.DeclaringType,
                ParameterTypes = method.GetParameters()
                                 .Select <ParameterInfo, Type>(p => p.ParameterType)
                                 .ToArray <Type>(),
                ReturnType = method.ReturnType ?? typeof(void)
            };
            _parameters = new SimpleParameter[parameters.Length];
            int positionOffset = method.IsStatic ? 0 : 1;

            for (int i = 0; i < parameters.Length; ++i)
            {
                _parameters[i] = new SimpleParameter(
                    this,
                    parameters[i].Position + positionOffset,
                    parameters[i].ParameterType,
                    null);
            }
            _ilGenerator = method.GetILGenerator();
        }
Esempio n. 2
0
        public void TestGenerateStubForVirtualMethod()
        {
            MethodInfo    methodInfo    = typeof(List <string>).GetMethod("Add");
            DynamicMethod dynamicMethod = Stubs.GenerateStubForVirtualMethod(methodInfo);
            int           count         = dynamicMethod.GetParameters().Length;

            Assert.AreEqual(methodInfo.GetParameters().Length, dynamicMethod.GetParameters().Length - 3);
            Assert.AreEqual(typeof(List <string>), dynamicMethod.GetParameters()[0].ParameterType);
            Assert.AreEqual(typeof(RuntimeMethodHandle), dynamicMethod.GetParameters()[count - 2].ParameterType);
            Assert.AreEqual(typeof(RuntimeTypeHandle), dynamicMethod.GetParameters()[count - 1].ParameterType);
        }
Esempio n. 3
0
        public void TestGenerateStubForConstructorNewobj()
        {
            ConstructorInfo constructorInfo = typeof(List <string>).GetConstructor(Type.EmptyTypes);
            DynamicMethod   dynamicMethod   = Stubs.GenerateStubForConstructor(constructorInfo, OpCodes.Newobj, false);
            int             count           = dynamicMethod.GetParameters().Length;

            Assert.AreEqual(constructorInfo.GetParameters().Length, dynamicMethod.GetParameters().Length - 2);
            Assert.AreEqual(typeof(List <string>), dynamicMethod.ReturnType);
            Assert.AreEqual(typeof(RuntimeMethodHandle), dynamicMethod.GetParameters()[count - 2].ParameterType);
            Assert.AreEqual(typeof(RuntimeTypeHandle), dynamicMethod.GetParameters()[count - 1].ParameterType);
        }
Esempio n. 4
0
        public void TestGenerateStubForStaticMethod()
        {
            MethodInfo    methodInfo    = typeof(Console).GetMethod("WriteLine", new[] { typeof(string) });
            DynamicMethod dynamicMethod = Stubs.GenerateStubForMethod(methodInfo);
            int           count         = dynamicMethod.GetParameters().Length;

            Assert.AreEqual(methodInfo.GetParameters().Length, dynamicMethod.GetParameters().Length - 2);
            Assert.AreEqual(methodInfo.GetParameters()[0].ParameterType, dynamicMethod.GetParameters()[0].ParameterType);
            Assert.AreEqual(typeof(RuntimeMethodHandle), dynamicMethod.GetParameters()[count - 2].ParameterType);
            Assert.AreEqual(typeof(RuntimeTypeHandle), dynamicMethod.GetParameters()[count - 1].ParameterType);
        }
        internal static void CreateDelegateTypeFor(TypeBuilder proxyType, DynamicMethod dynamicMethod, out Type delType, out MethodInfo invokeMethod)
        {
            ModuleBuilder modBuilder   = (ModuleBuilder)proxyType.Module;
            TypeBuilder   delegateType = modBuilder.DefineType($"{dynamicMethod.Name}Delegate_" + Guid.NewGuid().ToString("N"), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate));

            // Delegate .ctor
            ConstructorBuilder constructorBuilder = delegateType.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) });

            constructorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

            // Define the Invoke method for the delegate
            ParameterInfo[] parameters = dynamicMethod.GetParameters();
            Type[]          paramTypes = new Type[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                paramTypes[i] = parameters[i].ParameterType;
            }

            MethodBuilder methodBuilder = delegateType.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, dynamicMethod.ReturnType, paramTypes);

            for (int i = 0; i < parameters.Length; i++)
            {
                methodBuilder.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name);
            }

            methodBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

            delType      = delegateType.CreateTypeInfo().AsType();
            invokeMethod = delType.GetMethod("Invoke");
        }
Esempio n. 6
0
        public static void VerifyMethod(DynamicMethod method, string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Module module)
        {
            Assert.Equal(name, method.Name);
            Assert.Equal(attributes, method.Attributes);
            Assert.Equal(callingConvention, method.CallingConvention);

            Assert.Equal(returnType ?? typeof(void), method.ReturnType);
            Assert.Null(method.ReturnParameter);

            ParameterInfo[] parameters = method.GetParameters();
            if (parameterTypes == null)
            {
                Assert.Empty(parameters);
            }
            else
            {
                Assert.Equal(parameterTypes.Length, parameters.Length);
                for (int i = 0; i < parameterTypes.Length; i++)
                {
                    ParameterInfo parameter = parameters[i];
                    Assert.Equal(parameterTypes[i], parameter.ParameterType);
                    Assert.Equal(i, parameter.Position);
                }
            }

            Assert.Same(module, method.Module);
            Assert.Null(method.DeclaringType);

            Assert.True(method.InitLocals);
        }
Esempio n. 7
0
        public OperandReaderContext_DynamicMethod(DynamicMethod method)
        {
            this.name = method.Name;
            ILGenerator ILGen = method.GetILGenerator();

            this.maxStackSize = RTTypes.GetMaxStackSize(ILGen);
            this.@this        = method.DeclaringType;
            this.initLocals   = method.InitLocals;
            this.arguments    = method.GetParameters();
            InitVariables(ILGen);
            InitMethodSpec(method);
            //
            this.resolver = RTTypes.GetResolver(method);
            if (resolver != null)
            {
                this.ILBytes           = RTTypes.GetIL(resolver);
                this.resolveToken      = RTTypes.GetTokenResolver(resolver);
                this.resolveString     = RTTypes.GetStringResolver(resolver);
                this.resolveSignature  = RTTypes.GetSignatureResolver(resolver);
                this.typeFromHandle    = RTTypes.GetTypeFromHandleUnsafe();
                this.methodFromHandles = RTTypes.GetMethodFromHandles();
                this.fieldFromHandles  = RTTypes.GetFieldFromHandles();
            }
            else
            {
                this.ILBytes = new byte[ILGen.ILOffset];
                RTTypes.CopyILStream(ILGen, ILBytes);
                // TODO
            }
        }
        public static MethodInvokerDelegate GetMethodInvokerDelegate(DynamicMethod dynamicMethod)
        {
            IList <Type> methodParams = dynamicMethod.GetParameters().Select(param => param.ParameterType)
                                        .ToList();


            switch (methodParams.Count)
            {
            case 0:
                var func0 = (Func <object>)dynamicMethod.CreateDelegate(typeof(Func <object>));
                return((contextObj, args) => func0());

            case 1:
                var func1 = (Func <object, object>)dynamicMethod.CreateDelegate(typeof(Func <object, object>));
                return((contextObj, args) => func1(contextObj));

            case 2:
                Type funcDelegateType = typeof(Func <object, object, object>);
                var  func2            = (Func <object, object, object>)dynamicMethod.CreateDelegate(funcDelegateType);
                return((contextObj, args) => func2(contextObj, args[0]));

            case 3:
                funcDelegateType = typeof(Func <object, object, object, object>);
                var func3 = (Func <object, object, object, object>)dynamicMethod.CreateDelegate(funcDelegateType);
                return((contextObj, args) => func3(contextObj, args[0], args[1]));

            default:
                throw new NotSupportedException($"Don't support methods with {methodParams.Count} parameters");
            }
        }
Esempio n. 9
0
        /// <summary>
        /// 以托管代码默认约定调用动态方法。
        /// </summary>
        /// <param name="ilGen">ilGen</param>
        /// <param name="dynamicMethod">动态方法</param>
        public static ILGenerator Calli(this ILGenerator ilGen, DynamicMethod dynamicMethod)
        {
            // 保存引用。
            GCHandle.Alloc(dynamicMethod);

            return(ilGen.Calli(
                       dynamicMethod.GetFunctionPointer(),
                       dynamicMethod.ReturnType,
                       dynamicMethod.GetParameters().Map(item => item.ParameterType)));
        }
Esempio n. 10
0
        private Delegate CompileInternal(Type modelType, String template, OutputFormat outputFormat)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }

            DynamicMethod genMethod = new DynamicMethod("Build", typeof(String), new[] { modelType, typeof(IFormatProvider) }, true);

            genMethod.InitLocals = true;
#if !NETCOREAPP
            genMethod.DefineParameter(1, ParameterAttributes.In, "model");
            genMethod.DefineParameter(2, ParameterAttributes.In, "formatProvider");
#endif
            ILGenerator il                  = genMethod.GetILGenerator();
            InputParam  modelParam          = new InputParam(genMethod.GetParameters()[0]);
            InputParam  formatProviderParam = new InputParam(genMethod.GetParameters()[1]);
            Generator   generator           = new Generator(il, outputFormat, modelParam, formatProviderParam);
            Compile(template, generator);
            Delegate buildFunc = genMethod.CreateDelegate(typeof(Func <, ,>).MakeGenericType(modelType, typeof(IFormatProvider), typeof(String)));
            return(buildFunc);
        }
        private MethodBuilder CreateMethodProxy(MethodBuilder context, DynamicMethod target)
        {
            TypeBuilder   tb   = (TypeBuilder)context.DeclaringType;
            string        name = $".dmdproxy<{target.Name.Replace('.', '_')}>?{target.GetHashCode()}";
            MethodBuilder mb;

            // System.NotSupportedException: The invoked member is not supported before the type is created.

            /*
             * mb = tb.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Static) as MethodBuilder;
             * if (mb != null)
             *  return mb;
             */

            Type[] args = target.GetParameters().Select(param => param.ParameterType).ToArray();
            mb = tb.DefineMethod(
                name,
                System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.Private | System.Reflection.MethodAttributes.Static,
                CallingConventions.Standard,
                target.ReturnType,
                args
                );
            ILGenerator il = mb.GetILGenerator();

            // Load the DynamicMethod reference first.
            il.EmitReference(target);
            // Load any other arguments on top of that.
            il.Emit(OpCodes.Ldnull);
            il.Emit(OpCodes.Ldc_I4, args.Length);
            il.Emit(OpCodes.Newarr, typeof(object));
            for (int i = 0; i < args.Length; i++)
            {
                il.Emit(OpCodes.Dup);
                il.Emit(OpCodes.Ldc_I4, i);
                il.Emit(OpCodes.Ldarg, i);
                il.Emit(OpCodes.Stelem_Ref);
            }
            // Invoke the delegate and return its result.
            il.Emit(OpCodes.Callvirt, m_MethodBase_InvokeSimple);
            if (target.ReturnType == typeof(void))
            {
                il.Emit(OpCodes.Pop);
            }
            else if (target.ReturnType.IsValueType)
            {
                il.Emit(OpCodes.Unbox_Any, target.ReturnType);
            }
            il.Emit(OpCodes.Ret);

            return(mb);
        }
Esempio n. 12
0
        public void TestGenericConv2()
        {
            var gc3     = typeof(GenericConv3 <>);
            var gc3base = gc3.BaseType;

            var dyna = new DynamicMethod("op_Implicit", gc3base, new Type[] { gc3 }, gc3);

            // will crash because gc3 can't host this method - it has open generic parameters

            Assert.IsTrue(dyna.IsStatic);
            Assert.AreEqual("op_Implicit", dyna.Name);
            Assert.AreEqual(gc3base.MetadataToken, dyna.ReturnType.MetadataToken);
            Assert.AreEqual(gc3.MetadataToken, dyna.GetParameters()[0].ParameterType.MetadataToken);
        }
        public void DefineParameter_SetsParameterCorrectly()
        {
            Type[] mathArgs = { typeof(double), typeof(double) };

            var powerOf = new DynamicMethod("PowerOf",
                                            typeof(double),
                                            mathArgs,
                                            typeof(double).Module);

            ILGenerator il = powerOf.GetILGenerator(256);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Call, typeof(Math).GetMethod("Pow"));
            il.Emit(OpCodes.Ret);

            powerOf.DefineParameter(1, ParameterAttributes.In, "base");
            powerOf.DefineParameter(2, ParameterAttributes.Out, "exponent");

            object[] invokeArgs = { 2, 5 };
            object   objRet     = powerOf.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new CultureInfo("en-us"));

            ParameterInfo[] parameters = powerOf.GetParameters();

            Assert.Equal(32.0, objRet);

            Assert.Equal("base", parameters[0].Name);
            Assert.Equal("exponent", parameters[1].Name);

            Assert.Equal(typeof(double), parameters[0].ParameterType);
            Assert.Equal(typeof(double), parameters[1].ParameterType);

            Assert.Equal(ParameterAttributes.In, parameters[0].Attributes);
            Assert.Equal(ParameterAttributes.Out, parameters[1].Attributes);

            if (!PlatformDetection.IsMonoRuntime) // [ActiveIssue("https://github.com/dotnet/runtime/issues/36271")]
            {
                Assert.Empty(parameters[0].GetRequiredCustomModifiers());
                Assert.Empty(parameters[1].GetRequiredCustomModifiers());

                Assert.Empty(parameters[0].GetOptionalCustomModifiers());
                Assert.Empty(parameters[1].GetOptionalCustomModifiers());
            }
        }
Esempio n. 14
0
        public static IntPtr GetAddress(DynamicMethod dynamicMethod)
        {
            var ptr = GetDynamicMethodAddress(dynamicMethod);

            if (ptr == IntPtr.Zero)
            {
                var @params = Enumerable.Repeat((object)null, dynamicMethod.GetParameters().Length).ToArray();
                try
                {
                    dynamicMethod.Invoke(null, @params);
                }
                catch
                {
                    // ignored
                }
            }
            ptr = GetDynamicMethodAddress(dynamicMethod);
            return(ptr);
        }
Esempio n. 15
0
        private static Delegate CreateDynamicDelegate <TDelegate>(TDelegate first, TDelegate last, Delegate firstDelegate, Delegate lastDelegate) where TDelegate : class
        {
            MethodInfo    signature   = firstDelegate?.Method ?? lastDelegate.Method;
            DynamicMethod dynamic     = new DynamicMethod(string.Empty, signature.ReturnType == voidType ? null : signature.ReturnType, signature.GetParameters().Select(getParameterType).ToArray(), weakDelegateType);
            ILGenerator   il          = dynamic.GetILGenerator();
            LocalBuilder  suragate    = il.DeclareLocal(weakDelegateSuragateType);
            Label         noSuragate  = il.DefineLabel();
            Label         noDelegates = il.DefineLabel();

            il.Emit(OpCodes.Call, getCurrentMethodMethodInfo);
            il.Emit(OpCodes.Ldloca_S, suragate);
            il.Emit(OpCodes.Call, getCombinedHolderMethodInfo);
            il.Emit(OpCodes.Brfalse_S, noSuragate);
            il.Emit(OpCodes.Ldloc_S, suragate);
            il.Emit(OpCodes.Callvirt, getInvocationListMethodInfo);
            il.Emit(OpCodes.Castclass, typeof(TDelegate));
            il.Emit(OpCodes.Dup);
            il.Emit(OpCodes.Brfalse_S, noDelegates);
            for (int argIndex = 0; argIndex < dynamic.GetParameters().Length; argIndex++)
            {
                il.Emit(OpCodes.Ldarg, argIndex);
            }
            il.Emit(OpCodes.Callvirt, typeof(TDelegate).GetMethod("Invoke"));
            il.Emit(OpCodes.Ret);
            if (dynamic.ReturnType == null || dynamic.ReturnType == voidType)
            {
                il.MarkLabel(noDelegates);
                il.Emit(OpCodes.Pop);
                il.MarkLabel(noSuragate);
            }
            else
            {
                il.MarkLabel(noSuragate);
                il.Emit(OpCodes.Ldnull);
                il.MarkLabel(noDelegates);
            }
            il.Emit(OpCodes.Ret);
            return(dynamic.CreateDelegate((first ?? last).GetType()));
        }
Esempio n. 16
0
        public void ImplementOutParameters()
        {
            {
                var dyn = new DynamicMethod("TestMethod", typeof(void), new Type[] { typeof(Action).MakeByRefType(), typeof(byte).MakeByRefType(), typeof(Guid).MakeByRefType(), typeof(int) });
                var g   = dyn.GetILGenerator();

                var parameters = dyn.GetParameters();
                g.StoreDefaultValueForOutParameter(parameters[0]);
                g.StoreDefaultValueForOutParameter(parameters[1]);
                g.StoreDefaultValueForOutParameter(parameters[2]);
                g.Emit(OpCodes.Ret);

                var    d    = (DynamicWithOutParameters)dyn.CreateDelegate(typeof(DynamicWithOutParameters));
                Action a    = () => { };
                Byte   b    = 87;
                Guid   guid = Guid.NewGuid();
                d(out a, out b, ref guid, 6554);

                Assert.That(a, Is.Null);
                Assert.That(b, Is.EqualTo(0));
                Assert.That(guid, Is.EqualTo(Guid.Empty));
            }
        }
Esempio n. 17
0
    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]);
    }
Esempio n. 18
0
    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) };

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

        // <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,
        // 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);
        // </Snippet2>

        // <Snippet33>
        // 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");
        // </Snippet33>

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

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

        // <Snippet4>
        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 CultureInfo("en-us"));

        Console.WriteLine("hello.Invoke returned: " + objRet);
        // </Snippet4>

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

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

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

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

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

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

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

        // <Snippet29>
        if (hello.ReturnParameter == null)
        {
            Console.WriteLine("\r\nMethod has no return parameter.");
        }
        else
        {
            Console.WriteLine("\r\nReturn parameter: {0}", hello.ReturnParameter);
        }
        // </Snippet29>

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

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

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

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