Ejemplo n.º 1
0
        public void TestMethodImplementationFlags()
        {
            ConstructorBuilder cb = genClass.DefineConstructor(
                0, 0, new Type [0]);

            Assert.AreEqual(MethodImplAttributes.Managed | MethodImplAttributes.IL,
                            cb.GetMethodImplementationFlags(), "#A1");
            cb.SetImplementationFlags(MethodImplAttributes.OPTIL);
            Assert.AreEqual(MethodImplAttributes.OPTIL,
                            cb.GetMethodImplementationFlags(), "#A2");

            // Can not be called on a created type
            TypeBuilder        tb  = module.DefineType(genTypeName(), TypeAttributes.Public);
            ConstructorBuilder cb2 = tb.DefineConstructor(
                0, 0, new Type [0]);

            cb2.GetILGenerator().Emit(OpCodes.Ret);
            cb2.SetImplementationFlags(MethodImplAttributes.Managed);
            tb.CreateType();
            try {
                cb2.SetImplementationFlags(MethodImplAttributes.OPTIL);
                Assert.Fail("#B1");
            } catch (InvalidOperationException ex) {
                // Unable to change after type has been created
                Assert.AreEqual(typeof(InvalidOperationException), ex.GetType(), "#B2");
                Assert.IsNull(ex.InnerException, "#B3");
                Assert.IsNotNull(ex.Message, "#B4");
            }
        }
Ejemplo n.º 2
0
        private void BuildEngineDelegate()
        {
            string          name            = "Pkcs11GramEngineLoaderProxyDelegate";
            AssemblyName    assemblyName    = new AssemblyName(name);
            AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule(name);

            IList <MethodInfo> methods = _engine.GetType().GetMethods().ToArray();

            foreach (var item in methods)
            {
                TypeBuilder typeBuilder = moduleBuilder.DefineType($"{item.Name}",
                                                                   TypeAttributes.Public | TypeAttributes.AutoLayout | TypeAttributes.AnsiClass | TypeAttributes.Sealed,
                                                                   typeof(MulticastDelegate));

                ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName,
                                                                                      CallingConventions.Standard, item.GetParameters().Select(x => x.ParameterType).ToArray());
                constructorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime);

                MethodBuilder methodBuilder = typeBuilder.DefineMethod("Invoke",
                                                                       MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual,
                                                                       CallingConventions.Standard, item.ReturnType, item.GetParameters().Select(x => x.ParameterType).ToArray());
                methodBuilder.SetImplementationFlags(MethodImplAttributes.Runtime);

                DelegateType.Add(typeBuilder.CreateType());
            }
        }
        Type createDelegateType(string delegate_type_name, ModuleBuilder mb, Type ret_type, Type[] arg_types)
        {
            // Create delegate
            TypeBuilder delegate_type = mb.DefineType(delegate_type_name,
                                                      TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed |
                                                      TypeAttributes.AnsiClass | TypeAttributes.AutoClass,
                                                      typeof(System.MulticastDelegate));

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

            constructorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
            MethodBuilder methodBuilder = delegate_type.DefineMethod("Invoke",
                                                                     MethodAttributes.Public | MethodAttributes.HideBySig |
                                                                     MethodAttributes.NewSlot | MethodAttributes.Virtual,
                                                                     ret_type, arg_types);

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

            // Add [UnmanagedFunctionPointer(CallingConvention.Cdecl)] attribute for the delegate
            ConstructorInfo func_pointer_constructor =
                typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new Type[] { typeof(CallingConvention) });
            CustomAttributeBuilder ca_builder =
                new CustomAttributeBuilder(func_pointer_constructor, new object[] { CallingConvention.Cdecl });

            delegate_type.SetCustomAttribute(ca_builder);

            return(delegate_type.CreateType());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Builds the delegate for the given method info.
        /// </summary>
        /// <param name="mi">The method to build a delegate for.</param>
        /// <returns>The created delegate instance.</returns>
        private Delegate BuildDelegateForMethodInfo(MethodInfo mi)
        {
            AssemblyName    assemblyName  = new AssemblyName(mi.Name + "DynamicDelegate");
            AssemblyBuilder builder       = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder   moduleBuilder = builder.DefineDynamicModule(assemblyName.Name);

            TypeBuilder            typeBuilder = moduleBuilder.DefineType(mi.Name + "Delegate", TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate));
            CustomAttributeBuilder cab         = CreateUnmanagedCallingConvention();

            typeBuilder.SetCustomAttribute(cab);

            ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) });

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

            // Create the invoke method
            ParameterInfo[] parameters = mi.GetParameters();
            Type[]          paramTypes = new Type[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                paramTypes[i] = parameters[i].ParameterType;
            }

            // Define the Invoke method for the delegate
            MethodBuilder methodBuilder = typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, CallingConventions.Standard, mi.ReturnType, paramTypes);

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

            Type fullType = typeBuilder.CreateType();

            return(Delegate.CreateDelegate(fullType, mi));
        }
            private static Type CreateGenericFuncType(int paramCount)
            {
                string[] typeArgNames = new string[paramCount + 1];
                for (int i = 0; i < paramCount; i++)
                {
                    typeArgNames[i] = "T" + i;
                }
                typeArgNames[paramCount] = "TResult";

                TypeBuilder typeBuilder = module.DefineType("Func`" + paramCount, TypeAttributes.Sealed | TypeAttributes.Public, typeof(MulticastDelegate));

                GenericTypeParameterBuilder[] genericParameters = typeBuilder.DefineGenericParameters(typeArgNames);

                ConstructorBuilder constructor = typeBuilder.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(object), typeof(IntPtr) });

                constructor.SetImplementationFlags(MethodImplAttributes.CodeTypeMask);

                MethodBuilder invokeMethod = typeBuilder.DefineMethod("Invoke", MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public, genericParameters[paramCount], genericParameters.Take(paramCount).ToArray());

                invokeMethod.SetImplementationFlags(MethodImplAttributes.CodeTypeMask);
                for (int i = 0; i < paramCount; i++)
                {
                    invokeMethod.DefineParameter(i + 1, ParameterAttributes.None, genericParameters[i].Name);
                }
                return(typeBuilder.CreateType());
            }
Ejemplo n.º 6
0
        private static Type CreateDelegateType(BasicSignature signature)
        {
            string delTypeName = signature.UniqueName;

            TypeAttributes typeAttr = TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass;
            TypeBuilder    del      = CppLibrary.interopModule.DefineType(delTypeName, typeAttr, typeof(MulticastDelegate));

            if (signature.CallingConvention.HasValue)
            {
                ConstructorInfo        ufpa             = typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new Type [] { typeof(CallingConvention) });
                CustomAttributeBuilder unmanagedPointer = new CustomAttributeBuilder(ufpa, new object [] { signature.CallingConvention.Value });
                del.SetCustomAttribute(unmanagedPointer);
            }

            MethodAttributes   ctorAttr = MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public;
            ConstructorBuilder ctor     = del.DefineConstructor(ctorAttr, CallingConventions.Standard, new Type[] { typeof(object), typeof(System.IntPtr) });

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

            Type []          parameterTypes = signature.ParameterTypes.ToArray();
            MethodAttributes methodAttr     = MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual;

            MethodBuilder invokeMethod = del.DefineMethod("Invoke", methodAttr, signature.ReturnType, parameterTypes);

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

            return(del.CreateType());
        }
        protected Type CreateDelegateType(Type return_type, Type [] argument_types)
        {
            TypeBuilder type = module.DefineType(Guid.NewGuid().ToString(), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate));

//			var actor = typeof (MarshalAsAttribute).GetConstructor (new Type [] { typeof (UnmanagedType) });
//			Console.WriteLine(actor);

//			type.SetCustomAttribute (new CustomAttributeBuilder (typeof (MarshalAsAttribute).GetConstructor (new Type [] { typeof (UnmanagedType) }), new object [] { UnmanagedType.FunctionPtr }));

            ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type [] { typeof(object), typeof(int) });

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

            MethodBuilder method = null;

            method = type.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, return_type, argument_types);

            if (NeedsCustomMarshaler(return_type))
            {
                SetupParameter(method, 0, return_type);
            }

            for (int i = 1; i <= argument_types.Length; i++)
            {
                if (NeedsCustomMarshaler(argument_types [i - 1]))
                {
                    SetupParameter(method, i, argument_types [i - 1]);
                }
            }

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

            return(type.CreateTypeInfo().AsType());
        }
        public Type CreateCustomDelegate(Type returnType, params Type[] parameterTypes)
        {
            AssemblyName assembly = new AssemblyName();

            assembly.Name = "CreateCustomDelegateAssembly";

            AssemblyBuilder assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(assembly, AssemblyBuilderAccess.RunAndSave);

            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("TempModule");

            TypeBuilder typeBuilder =
                moduleBuilder.DefineType("TempDelegateType",
                                         TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class |
                                         TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate));

            ConstructorBuilder constructorBuilder =
                typeBuilder.DefineConstructor(
                    MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
                    CallingConventions.Standard, new Type[] { typeof(object), typeof(int) });

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

            MethodBuilder methodBuilder =
                typeBuilder.DefineMethod("Invoke",
                                         MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot |
                                         MethodAttributes.Virtual, returnType, parameterTypes);

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

            return(typeBuilder.CreateType());
        }
        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");
        }
Ejemplo n.º 10
0
            private Type BuildDelegate(TypeBuilder type, MethodInfo method, Hashtable ctors, Hashtable invocations)
            {
                TypeBuilder d = type.DefineNestedType(method.Name + "Handler",
                                                      TypeAttributes.Class | TypeAttributes.NestedPrivate | TypeAttributes.Sealed,
                                                      typeof(System.MulticastDelegate));

                ParameterInfo[] parameters  = method.GetParameters();
                Type[]          paramTypes1 = new Type[parameters.Length];
                Type[]          paramTypes2 = new Type[parameters.Length + 2];
                for (int i = 0; i < parameters.Length; i++)
                {
                    paramTypes1[i] = parameters[i].ParameterType;
                    paramTypes2[i] = parameters[i].ParameterType;
                }
                paramTypes2[parameters.Length]     = typeof(AsyncCallback);
                paramTypes2[parameters.Length + 1] = typeof(object);
                MethodAttributes theAttr = MethodAttributes.Public | MethodAttributes.HideBySig
                                           | MethodAttributes.NewSlot | MethodAttributes.Virtual;
                MethodImplAttributes theImplAttr = MethodImplAttributes.Runtime | MethodImplAttributes.Managed;
                ConstructorBuilder   ctor        = d.DefineConstructor(MethodAttributes.Public,
                                                                       CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) });

                ctor.SetImplementationFlags(theImplAttr);
                ctors.Add(method.Name, ctor);
                d.DefineMethod("Invoke", theAttr, method.ReturnType, paramTypes1).SetImplementationFlags(theImplAttr);
                MethodBuilder invocation = d.DefineMethod("BeginInvoke", theAttr, typeof(IAsyncResult), paramTypes2);

                invocation.SetImplementationFlags(theImplAttr);
                invocations.Add(method.Name, invocation);
                d.DefineMethod("EndInvoke", theAttr, method.ReturnType,
                               new Type[] { typeof(IAsyncResult) }).SetImplementationFlags(theImplAttr);
                return(d);
            }
Ejemplo n.º 11
0
        public static IEmittedDelegate GenerateDelegateType(this ModuleBuilder modBuilder, MethodInfo targetMethod, bool isInstanceToStatic)
        {
            // Create a delegate that has the same signature as the method we would like to hook up to
            int identifier = Interlocked.Increment(ref DelegateCounter);

            string delegateName = modBuilder.Assembly.GetName().Name + ".Delegates.D" + identifier;

            var typeBuilder = modBuilder.DefineType(delegateName, DelegateTypeAttributes, typeof(MulticastDelegate));

            ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(
                DelegateConstructorAttributes, CallingConventions.Standard, DelegateConstructorTypes);

            constructorBuilder.SetImplementationFlags(DelegateMemberImplemenationFlags);

            // Grab the parameters of the method
            Type[] paramTypes = GetParamTypes(targetMethod, isInstanceToStatic);

            // Define the Invoke method for the delegate
            var methodBuilder = typeBuilder.DefineMethod(
                "Invoke", DelegateInvokeMethodAttributes, targetMethod.ReturnType, paramTypes);

            methodBuilder.SetImplementationFlags(DelegateMemberImplemenationFlags);

            // bake it!
            Type t = typeBuilder.CreateType();

            return(new EmittedDelegate {
                Type = t, InvokeMethod = methodBuilder, Identifier = identifier
            });
        }
        public void TestImplFlags()
        {
            AssemblyName myAssemblyName = new AssemblyName();

            myAssemblyName.Name = "TempAssembly";
            AssemblyBuilder myAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);

            ModuleBuilder myModuleBuilder = TestLibrary.Utilities.GetModuleBuilder(myAssemblyBuilder, "Module1");

            TypeBuilder        myTypeBuilder = myModuleBuilder.DefineType("TempClass", TypeAttributes.Public);
            ConstructorBuilder myConstructor = myTypeBuilder.DefineConstructor(
                MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) });

            myConstructor.SetImplementationFlags(MethodImplAttributes.Runtime);

            MethodImplAttributes myMethodAttributes = myConstructor.MethodImplementationFlags;

            int myAttribValue = (int)myMethodAttributes;

            FieldInfo[] myFieldInfo = typeof(MethodImplAttributes).GetFields(BindingFlags.Public | BindingFlags.Static);

            for (int i = 0; i < myFieldInfo.Length; i++)
            {
                if (myFieldInfo[i].Name == "Runtime")
                {
                    int myFieldValue = (int)myFieldInfo[i].GetValue(null);
                    Assert.Equal(myFieldValue, (myFieldValue & myAttribValue));
                }
            }
        }
Ejemplo n.º 13
0
        public void SetImplementationFlagsIfPresent(MethodDefinition methodDefintion, ConstructorBuilder constructorBuilder)
        {
            System.Reflection.MethodImplAttributes methodImplFlags = default(System.Reflection.MethodImplAttributes);
            bool setFlags = false;

            if (methodDefintion.IsRuntime)
            {
                methodImplFlags |= System.Reflection.MethodImplAttributes.Runtime;

                setFlags = true;
            }

            if (methodDefintion.IsManaged)
            {
                methodImplFlags |= System.Reflection.MethodImplAttributes.Managed;

                setFlags = true;
            }

            if (setFlags)
            {
                //methodDefintion.IsManaged;
                constructorBuilder.SetImplementationFlags(methodImplFlags);
            }
        }
Ejemplo n.º 14
0
        public static object InvokeProperty(System.Windows.Forms.Control obj, string propertyName, params object[] paramValues)
        {
            Delegate del = null;
            string   key = obj.GetType().Name + "." + propertyName;
            Type     tp;

            lock (methodLookup)
            {
                if (methodLookup.Contains(key))
                {
                    tp = (Type)methodLookup[key];
                }
                else
                {
                    Type[] paramList = new Type[obj.GetType().GetProperty(propertyName).GetSetMethod().GetParameters().Length];
                    int    n         = 0;
                    foreach (ParameterInfo pi in obj.GetType().GetProperty(propertyName).GetSetMethod().GetParameters())
                    {
                        paramList[n++] = pi.ParameterType;
                    }
                    TypeBuilder        typeB = builder.DefineType("Del_" + obj.GetType().Name + "_" + propertyName, TypeAttributes.Class | TypeAttributes.AutoLayout | TypeAttributes.Public | TypeAttributes.Sealed, typeof(MulticastDelegate), PackingSize.Unspecified);
                    ConstructorBuilder conB  = typeB.DefineConstructor(MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) });
                    conB.SetImplementationFlags(MethodImplAttributes.Runtime);
                    MethodBuilder mb = typeB.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, obj.GetType().GetProperty(propertyName).GetSetMethod().ReturnType, paramList);
                    mb.SetImplementationFlags(MethodImplAttributes.Runtime);
                    tp = typeB.CreateType();
                    methodLookup.Add(key, tp);
                }
            }

            del = MulticastDelegate.CreateDelegate(tp, obj, obj.GetType().GetProperty(propertyName).GetSetMethod().Name);
            return(obj.Invoke(del, paramValues));
        }
Ejemplo n.º 15
0
        // http://blog.bittercoder.com/PermaLink,guid,a770377a-b1ad-4590-9145-36381757a52b.aspx
        private static Type CreateDelegateType(string name, Type retType, Type[] argTypes)
        {
            if (delegateModuleBuilder == null)
            {
                AssemblyName assembly = new AssemblyName();
                assembly.Name = "CustomDelegateAssembly";
                AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assembly, AssemblyBuilderAccess.Run);
                delegateModuleBuilder = assemblyBuilder.DefineDynamicModule("CustomDelegateModule");
            }

            TypeBuilder typeBuilder = delegateModuleBuilder.DefineType(name,
                                                                       TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class |
                                                                       TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate));

            ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(
                MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
                CallingConventions.Standard, constructorArgTypes);

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

            MethodBuilder methodBuilder = typeBuilder.DefineMethod("Invoke",
                                                                   MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot |
                                                                   MethodAttributes.Virtual, retType, argTypes);

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

            return(typeBuilder.CreateType());
        }
Ejemplo n.º 16
0
        public Type CreateDelegateType(MethodInfo method)
        {
            string nameBase = string.Format("{0}{1}", method.DeclaringType.Name, method.Name);
            string name     = GetUniqueName(nameBase);

            var typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Sealed | TypeAttributes.Public, typeof(MulticastDelegate));

            ConstructorBuilder constructor = typeBuilder.DefineConstructor(MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
                                                                           CallingConventions.Standard, new[] { typeof(object), typeof(IntPtr) });

            constructor.SetImplementationFlags(MethodImplAttributes.CodeTypeMask);

            ParameterInfo[] parameters = method.GetParameters();

            MethodBuilder invokeMethod = typeBuilder.DefineMethod("Invoke", MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Public,
                                                                  method.ReturnType, parameters.Select(p => p.ParameterType).ToArray());

            invokeMethod.SetImplementationFlags(MethodImplAttributes.CodeTypeMask);

            for (int i = 0; i < parameters.Length; i++)
            {
                var parameter = parameters[i];
                invokeMethod.DefineParameter(i + 1, ParameterAttributes.None, parameter.Name);
            }

            return(typeBuilder.CreateType());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Delegate is a single method type.
        /// </summary>
        public Type BuildDelegateType <TypeT>(TypeT queryType, string methodName) where TypeT : Type
        {
            MethodInfo methodInfo = queryType.GetMethod(methodName);

            if (methodInfo == null)
            {
                return(null);
            }

            TypeBuilder        typeBlder = _builder.DefineType(string.Format("{0}.{1}_Delegate", queryType.FullName, methodName), ClassTypeAttributes, typeof(MulticastDelegate), PackingSize.Unspecified);
            ConstructorBuilder conBlder  = typeBlder.DefineConstructor(ConstructorAttributes, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) });

            conBlder.SetImplementationFlags(MethodImplAttributes.Runtime);

            ParameterInfo[] parameters = methodInfo.GetParameters();
            Type[]          paramTypes = new Type[parameters.Length];
            for (int n = 0; n < parameters.Length; n++)
            {
                paramTypes[n] = parameters[n].ParameterType;
            }

            Type          methodReturnT = methodInfo.ReturnType;
            MethodBuilder mb            = typeBlder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, methodReturnT, paramTypes);

            mb.SetImplementationFlags(MethodImplAttributes.Runtime);

            return(typeBlder.CreateType());
        }
Ejemplo n.º 18
0
        TypeGen ImplementDelegate()
        {
            TypeGen tg = new TypeGen(owner, name, attrs, typeof(MulticastDelegate), Type.EmptyTypes);

            ConstructorBuilder cb = tg.Public.RuntimeImpl.Constructor()
                                    .Parameter(typeof(object), "object")
                                    .Parameter(typeof(IntPtr), "method")
                                    .GetConstructorBuilder();

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

            MethodBuilder mb = tg.Public.Virtual.RuntimeImpl.Method(typeof(IAsyncResult), "BeginInvoke")
                               .CopyParameters(Parameters)
                               .UncheckedParameter(typeof(AsyncCallback), "callback")
                               .UncheckedParameter(typeof(object), "object")
                               .GetMethodBuilder();

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

            mb = tg.Public.Virtual.RuntimeImpl.Method(ReturnType, "EndInvoke")
                 .Parameter(typeof(IAsyncResult), "result")
                 .GetMethodBuilder();
            mb.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

            mb = tg.Public.Virtual.RuntimeImpl.Method(ReturnType, "Invoke")
                 .CopyParameters(Parameters)
                 .GetMethodBuilder();
            mb.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

            AttributeGen.ApplyList(ref customAttributes, tg.TypeBuilder.SetCustomAttribute);

            return(tg);
        }
Ejemplo n.º 19
0
        private static Type CreateDelegateType(Type returnType, Type[] paramTypes)
        {
            ModuleBuilder moduleBuilder = InitModuleBuilder();
            TypeBuilder   typeBuilder   = moduleBuilder.DefineType("DelegateSignature" + knownSignatures.Count,
                                                                   TypeAttributes.Public | TypeAttributes.Class |
                                                                   TypeAttributes.Sealed | TypeAttributes.AnsiClass |
                                                                   TypeAttributes.AutoClass, typeof(MulticastDelegate));
            MethodBuilder methodBuilder = typeBuilder.DefineMethod("Invoke",
                                                                   MethodAttributes.Public | MethodAttributes.HideBySig |
                                                                   MethodAttributes.NewSlot |
                                                                   MethodAttributes.Virtual, CallingConventions.Standard,
                                                                   returnType, paramTypes);

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

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

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

            typeBuilder.SetCustomAttribute(
                new CustomAttributeBuilder(
                    typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new[] { typeof(CallingConvention) }),
                    new object[] { CallingConvention.StdCall }));
            Type delegateType = typeBuilder.CreateType();

            return(delegateType);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Uses reflection to emit the given <see cref="ConstructorInfo"/> body for the given type.
        /// </summary>
        /// <param name="typeBuilder">
        /// The <see cref="TypeBuilder"/>.
        /// </param>
        /// <param name="constructorInfo">
        /// The <see cref="ConstructorInfo"/>.
        /// </param>
        public static void Emit(TypeBuilder typeBuilder, ConstructorInfo constructorInfo)
        {
            // Define the default constructor attributes.
            const MethodAttributes constructorAttributes = MethodAttributes.Public |
                                                           MethodAttributes.HideBySig |
                                                           MethodAttributes.SpecialName |
                                                           MethodAttributes.RTSpecialName;

            // Get the parameters.
            Type[] parameterTypes = constructorInfo.GetParameters().Select(p => p.ParameterType).ToArray();

            // Define the constructor.
            ConstructorBuilder constructor = typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, parameterTypes);

            ILGenerator il = constructor.GetILGenerator();

            // ReSharper disable once BitwiseOperatorOnEnumWithoutFlags
            constructor.SetImplementationFlags(MethodImplAttributes.IL | MethodImplAttributes.Managed);

            // Load all constructor arguments. Note argument 0 is 'this' pointer, so you must emit one more.
            for (int i = 0; i <= parameterTypes.Length; i++)
            {
                il.Emit(OpCodes.Ldarg_S, i);
            }

            // Call the base constructor and return.
            il.Emit(OpCodes.Call, constructorInfo);
            il.Emit(OpCodes.Ret);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Defines a new delegate type.
        /// </summary>
        public static System.Type DefineDelegateType(
            string fullTypeName,
            ModuleBuilder moduleBuilder,
            System.Type returnType,
            System.Type[] parameterTypes)
        {
            TypeBuilder delegateBuilder =
                moduleBuilder.DefineType(
                    fullTypeName,
                    TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass |
                    TypeAttributes.AutoClass, typeof(MulticastDelegate));

            // Define a special constructor
            ConstructorBuilder constructorBuilder =
                delegateBuilder.DefineConstructor(
                    MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public,
                    CallingConventions.Standard, new System.Type[] { typeof(object), typeof(IntPtr) });

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

            // Define the Invoke method for the delegate

            MethodBuilder methodBuilder = delegateBuilder.DefineMethod("Invoke",
                                                                       MethodAttributes.Public | MethodAttributes.HideBySig
                                                                       | MethodAttributes.NewSlot | MethodAttributes.Virtual,
                                                                       returnType, parameterTypes);

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

            return(delegateBuilder.CreateType());
        }
Ejemplo n.º 22
0
        private static ConstructorBuilder DefineConstructor(TypeBuilder typeBuilder, System.Type parentType)
        {
            const MethodAttributes constructorAttributes = MethodAttributes.Public |
                                                           MethodAttributes.HideBySig | MethodAttributes.SpecialName |
                                                           MethodAttributes.RTSpecialName;

            ConstructorBuilder constructor =
                typeBuilder.DefineConstructor(constructorAttributes, CallingConventions.Standard, new System.Type[0]);

            var baseConstructor = parentType.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new System.Type[0], null);

            // if there is no default constructor, or the default constructor is private/internal, call System.Object constructor
            // this works, but the generated assembly will fail PeVerify (cannot use in medium trust for example)
            if (baseConstructor == null || baseConstructor.IsPrivate || baseConstructor.IsAssembly)
            {
                baseConstructor = defaultBaseConstructor;
            }

            ILGenerator IL = constructor.GetILGenerator();

            constructor.SetImplementationFlags(MethodImplAttributes.IL | MethodImplAttributes.Managed);

            IL.Emit(OpCodes.Ldarg_0);
            IL.Emit(OpCodes.Call, baseConstructor);
            IL.Emit(OpCodes.Ret);

            return(constructor);
        }
Ejemplo n.º 23
0
 protected override void CreateMember()
 {
     _cb = Owner.TypeBuilder.DefineConstructor(_attributes | MethodAttributes.HideBySig, IsStatic ? CallingConventions.Standard : CallingConventions.HasThis, ParameterTypes);
     if (_implFlags != 0)
     {
         _cb.SetImplementationFlags(_implFlags);
     }
 }
Ejemplo n.º 24
0
    public static void Main()
    {
        // Create a dynamic assembly and module to contain the
        // subclass of MulticastDelegate that we will create

        AssemblyName asmName = new AssemblyName();

        asmName.Name = "DynamicAssembly";

        AssemblyBuilder asmBuilder =
            AppDomain.CurrentDomain.DefineDynamicAssembly(
                asmName, AssemblyBuilderAccess.Run);

        ModuleBuilder modBuilder = asmBuilder.DefineDynamicModule
                                       ("DynamicModule");

        TypeBuilder typeBuilder = modBuilder.DefineType("MyType",
                                                        TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed,
                                                        typeof(System.MulticastDelegate));

        ConstructorBuilder cb = typeBuilder.DefineConstructor(
            MethodAttributes.Public | MethodAttributes.HideBySig |
            MethodAttributes.RTSpecialName | MethodAttributes.SpecialName,
            CallingConventions.Standard,
            new Type[] { typeof(Object), typeof(IntPtr) });

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

        MethodBuilder mb = typeBuilder.DefineMethod(
            "Invoke",
            MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.
            HideBySig,
            typeof(void),
            new Type[] { typeof(int) });

        mb.SetImplementationFlags(MethodImplAttributes.Runtime |
                                  MethodImplAttributes.Managed);
        ParameterBuilder pb = mb.DefineParameter(1, ParameterAttributes.HasFieldMarshal, "foo");

        pb.SetMarshal(UnmanagedMarshal.DefineUnmanagedMarshal(UnmanagedType.I2));

        // Create an instance of the delegate type and invoke it -- just to test

        Type     myDelegateType = typeBuilder.CreateType();
        Delegate d = Delegate.CreateDelegate(myDelegateType, typeof
                                             (Testing), "Method");

        d.DynamicInvoke(new object[] { 8 });

        DelegateList delegateList = new DelegateList();

        delegateList.del = d;
        IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(delegateList));

        // The execption seems to occur at this statement:
        Marshal.StructureToPtr(delegateList, ptr, false);
    }
Ejemplo n.º 25
0
        /// <summary>
        /// Get the event delegate for specified method in the source interface. Create a new one if necessary
        /// </summary>
        /// <param name="index">Function index</param>
        /// <returns>The delegate type</returns>
        public Type GetEventDelegate(InterfaceMemberInfo memberInfo)
        {
            TypeInfo type = memberInfo.RefTypeInfo;

            using (TypeAttr attr = type.GetTypeAttr())
            {
                // Create m_delegateTypes on demand
                if (m_delegateTypes == null)
                {
                    m_delegateTypes = new Dictionary <InterfaceMemberInfo, Type>();
                }

                //
                // Check if we already have a delegate type for method n
                //
                if (!m_delegateTypes.ContainsKey(memberInfo))
                {
                    //
                    // If not, create a new delegate
                    //
                    FuncDesc func = type.GetFuncDesc(memberInfo.Index);

                    string eventName    = type.GetDocumentation(func.memid);
                    string delegateName = m_info.GetRecommendedManagedName(m_convInterface.RefTypeInfo, ConvType.Interface, true) + "_" + type.GetDocumentation(func.memid) + "EventHandler";

                    // Deal with name collisions
                    delegateName = m_info.GetUniqueManagedName(delegateName);

                    TypeBuilder delegateTypeBuilder = m_info.ModuleBuilder.DefineType(
                        delegateName,
                        TypeAttributes.Public | TypeAttributes.Sealed,
                        typeof(MulticastDelegate)
                        );

                    // Create constructor for the delegate
                    ConstructorBuilder delegateCtorBuilder = delegateTypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[] { typeof(Object), typeof(UIntPtr) });
                    delegateCtorBuilder.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);

                    // Create methods for the delegate
                    InterfaceInfo interfaceInfoForDelegate = new InterfaceInfo(m_info, delegateTypeBuilder, false, type, attr, false, true);
                    interfaceInfoForDelegate.AllowNewEnum = !m_convInterface.ImplementsIEnumerable;
                    ConvCommon.CreateMethodForDelegate(interfaceInfoForDelegate, func, memberInfo.Index);

                    // Emit ComVisibleAttribute(false)
                    delegateTypeBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForComVisible(false));

                    // Emit TypeLibTypeAttribute(TypeLibTypeFlags.FHidden) to hide it from object browser in VB
                    delegateTypeBuilder.SetCustomAttribute(CustomAttributeHelper.GetBuilderForTypeLibType(TypeLibTypeFlags.FHidden));

                    // Create the delegate
                    m_delegateTypes[memberInfo] = delegateTypeBuilder.CreateType();
                }
            }

            return(m_delegateTypes[memberInfo]);
        }
        public void MethodImplementationFlags_SetToCustomValue()
        {
            TypeBuilder        type        = Helpers.DynamicType(TypeAttributes.Public);
            ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) });

            constructor.SetImplementationFlags(MethodImplAttributes.Runtime);
            MethodImplAttributes methodImplementationFlags = constructor.MethodImplementationFlags;

            Assert.Equal(MethodImplAttributes.Runtime, constructor.MethodImplementationFlags);
        }
Ejemplo n.º 27
0
        // Delegate type created here ignores firstArgument (if we have one)
        Type CreateDelegateType(ModuleBuilder modBuilder)
        {
            TypeBuilder   typeBuilder;
            MethodBuilder methodBuilder;

            XlParameterInfo[] paramInfos = Parameters;
            Type[]            paramTypes = Array.ConvertAll <XlParameterInfo, Type>(paramInfos,
                                                                                    delegate(XlParameterInfo pi)
                                                                                    { return(pi.DelegateParamType); });

            // Create a delegate that has the same signature as the method we would like to hook up to
            typeBuilder = modBuilder.DefineType("f" + Index++ + "Delegate",
                                                TypeAttributes.Class | TypeAttributes.Public |
                                                TypeAttributes.Sealed,
                                                typeof(System.MulticastDelegate));
            ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(
                MethodAttributes.RTSpecialName | MethodAttributes.HideBySig |
                MethodAttributes.Public, CallingConventions.Standard,
                new Type[] { typeof(object), typeof(int) });

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

            // Build up the delegate
            // Define the Invoke method for the delegate
            methodBuilder = typeBuilder.DefineMethod("Invoke",
                                                     MethodAttributes.Public | MethodAttributes.HideBySig |
                                                     MethodAttributes.NewSlot | MethodAttributes.Virtual,
                                                     HasReturnType ? ReturnType.DelegateParamType : typeof(void),
                                                     // What here for macro? null or Void ?
                                                     paramTypes);
            methodBuilder.SetImplementationFlags(MethodImplAttributes.Runtime |
                                                 MethodImplAttributes.Managed);

            // Set Marshal Attributes for return type
            if (HasReturnType && ReturnType.MarshalAsAttribute != null)
            {
                ParameterBuilder pb = methodBuilder.DefineParameter(0, ParameterAttributes.None, null);
                pb.SetCustomAttribute(ReturnType.MarshalAsAttribute);
            }

            // ... and the parameters
            for (int i = 1; i <= paramInfos.Length; i++)
            {
                CustomAttributeBuilder b = paramInfos[i - 1].MarshalAsAttribute;
                if (b != null)
                {
                    ParameterBuilder pb = methodBuilder.DefineParameter(i, ParameterAttributes.None, null);
                    pb.SetCustomAttribute(b);
                }
            }

            // Bake the type and get the delegate
            return(typeBuilder.CreateType());
        }
        public void SetImplementationFlags_TypeAlreadyCreated_ThrowsInvalidOperationException()
        {
            TypeBuilder        type        = Helpers.DynamicType(TypeAttributes.Public);
            ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]);

            constructor.GetILGenerator().Emit(OpCodes.Ret);

            Type createdType = type.CreateTypeInfo().AsType();

            Assert.Throws <InvalidOperationException>(() => constructor.SetImplementationFlags(MethodImplAttributes.Runtime));
        }
Ejemplo n.º 29
0
            /// <summary>
            /// Dynamically creates (and returns the type of) a delegate class with the given
            /// name and type signature.
            /// </summary>
            private Type CreateDelegateType(string name)
            {
                TypeBuilder typeBuilder = Driver._dynamicModuleBuilder.DefineType(name,
                                                                                  TypeAttributes.Class | TypeAttributes.Public |
                                                                                  TypeAttributes.Sealed | TypeAttributes.AnsiClass |
                                                                                  TypeAttributes.AutoClass, typeof(System.MulticastDelegate));

                // Add a '[UnmanagedFunctionPointer(CallingConvention.Cdecl)]' attribute to the delegate
                typeBuilder.SetCustomAttribute(new CustomAttributeBuilder(
                                                   typeof(UnmanagedFunctionPointerAttribute).GetConstructor(new Type[] { typeof(CallingConvention) }),
                                                   new object[] { CallingConvention.Cdecl }));

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

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

                MethodBuilder methodBuilder = typeBuilder.DefineMethod("Invoke", MethodAttributes.Public |
                                                                       MethodAttributes.HideBySig | MethodAttributes.NewSlot |
                                                                       MethodAttributes.Virtual,
                                                                       ReturnType, ParameterTypes);

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

                // For the return type and any parameter types
                for (int i = 0; i < ParameterTypes.Length + 1; i++)
                {
                    UnmanagedType?marshalAs;
                    if (i == 0)
                    {
                        marshalAs = MarshalTypeAs(ReturnType);
                    }
                    else
                    {
                        marshalAs = MarshalTypeAs(ParameterTypes[i - 1]);
                    }

                    if (marshalAs != null)
                    {
                        // Add a MarshalAs attribute to the return/parameter
                        ParameterBuilder pb = methodBuilder.DefineParameter(i, ParameterAttributes.None, null);
                        pb.SetCustomAttribute(new CustomAttributeBuilder(
                                                  typeof(MarshalAsAttribute).GetConstructor(new Type[] { typeof(UnmanagedType) }),
                                                  new object[] { marshalAs.Value }));
                    }
                }
                return(typeBuilder.CreateType());
            }
        public static Type FromMethodBase(MethodBase target)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target cannot be null");
            }

            if (implementations [target] != null)
            {
                return((Type)implementations [target]);
            }

            TypeBuilder type = module.DefineType(Guid.NewGuid().ToString(), TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.AnsiClass | TypeAttributes.AutoClass, typeof(MulticastDelegate));

            type.SetCustomAttribute(new CustomAttributeBuilder(typeof(MarshalAsAttribute).GetConstructor(new Type [] { typeof(UnmanagedType) }), new object [] { UnmanagedType.FunctionPtr }));

            ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type [] { typeof(object), typeof(int) });

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

            ParameterInfo [] parameters  = target.GetParameters();
            Type []          param_types = new Type [parameters.Length];

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

            MethodBuilder method = null;

            if (target is ConstructorInfo)
            {
                method = type.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, null, param_types);
            }
            if (target is MethodInfo)
            {
                method = type.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, ((MethodInfo)target).ReturnType, param_types);
            }
            if (method == null)
            {
                throw new ArgumentException("target must be a Constructor or a Method");
            }

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

            implementations [target] = type.CreateType();

            return((Type)implementations [target]);
        }