Inheritance: System.Reflection.ConstructorInfo, IClrProgramItem, IDetachItem
Example #1
0
 public ILConstructorDebugImpl(ConstructorBuilder constructor, IILGenForbidenInstructions forbidenInstructions, SourceCodeWriter sourceCodeWriter)
 {
     _constructor = constructor;
     _sourceCodeWriter = sourceCodeWriter;
     _forbidenInstructions = forbidenInstructions;
     _expectedLength = 64;
 }
		/// <summary>
		///   Defines an inner Delegate type for the method to be invoked from Objective-C runtime.
		/// </summary>
		// TODO: Refactor
		private Type DefineDelegate (TypeBuilder typeBuilder, MethodInfo methodInfo, out ConstructorBuilder constructorBuilder)
		{
			// Get info about the target method
			Type returnType = GetReturnType (methodInfo);
			Type nativeReturnType = TypeHelper.GetNativeType (returnType, this.Is64Bits);
			Type[] nativeParameterTypes = TypeHelper.GetNativeParameterTypes (methodInfo, this.Is64Bits);

			// TODO: Refactor
			// Remove first parameter of the extension method
			nativeParameterTypes = ArrayHelper.TrimLeft (nativeParameterTypes, 1);

			// Create the array of parameters for the delegate's invoke method
			nativeParameterTypes = ArrayHelper.Prepend (nativeParameterTypes, typeof(IntPtr), typeof(IntPtr));

			// Assign some names to parameters (for easy debugging)
			String[] parameterNames = TypeHelper.GetParameterNames (methodInfo);

			// TODO: Refactor
			// Remove first parameter of the extension method
			parameterNames = ArrayHelper.TrimLeft (parameterNames, 1);

			String[] nativeParameterNames = new String[nativeParameterTypes.Length];
			Array.Copy (parameterNames, 0, nativeParameterNames, 2, parameterNames.Length);
			nativeParameterNames [0] = "receiver";
			nativeParameterNames [1] = "selector";

			// Create a unique delegate name
			String name = GetUniqueName (methodInfo) + "_Invoker";

			// Create a delegate
			TypeBuilder delegateBuilder = EmitHelper.DefineNestedDelegate (typeBuilder, name, nativeReturnType, nativeParameterTypes, nativeParameterNames, out constructorBuilder);

			// Generate the type
			return delegateBuilder.CreateType ();
		}
Example #3
0
		internal ConstructorEmitter(AbstractTypeEmitter maintype, params ArgumentReference[] arguments)
		{
			this.maintype = maintype;

			var args = ArgumentsUtil.InitializeAndConvert(arguments);

			builder = maintype.TypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, args);
		}
 internal void Compile(ConstructorBuilder c)
 {
     if (Builder == null)
     {
         int ofs = (c.IsStatic ? 0 : 1);
         Builder = c.DefineParameter(this.Index + ofs, this.Attributes, this.Name);
     }
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="ConstructorBuilder"/> class
		/// with the specified parameters.
		/// </summary>
		/// <param name="typeBuilder">Associated <see cref="TypeBuilderHelper"/>.</param>
		/// <param name="constructorBuilder">A <see cref="ConstructorBuilder"/></param>
		public ConstructorBuilderHelper(TypeBuilderHelper typeBuilder, ConstructorBuilder constructorBuilder)
			: base(typeBuilder)
		{
			if (constructorBuilder == null) throw new ArgumentNullException("constructorBuilder");

			_constructorBuilder = constructorBuilder;
			_constructorBuilder.SetCustomAttribute(Type.Assembly.BLToolkitAttribute);
		}
Example #6
0
 public static void DefineParams(ConstructorBuilder constructorBuilder, IEnumerable<RppParameterInfo> constructorParams)
 {
     int index = 1;
     foreach (var param in constructorParams)
     {
         constructorBuilder.DefineParameter(index++, ParameterAttributes.None, RppClass.StringConstructorArgName(param.Name));
     }
 }
Example #7
0
		internal EasyConstructor( AbstractEasyType maintype, params ArgumentReference[] arguments )
		{
			_maintype = maintype;

			Type[] args = ArgumentsUtil.InitializeAndConvert( arguments );
			
			_builder = maintype.TypeBuilder.DefineConstructor( 
				 MethodAttributes.Public, CallingConventions.Standard, args );
		}
        private void EnhanceType(TypeBuilder mainType, FieldBuilder handlerFieldBuilder, ConstructorBuilder constructorBuilder)
        {
            Assert.IsTrue( !m_enhanceInvoked );

            Assert.IsNotNull(mainType);
            Assert.IsNotNull(handlerFieldBuilder);
            Assert.IsNotNull(constructorBuilder);

            m_enhanceInvoked = true;
        }
 protected void DefineLoaderType(ConstructorBuilder factoryConstructorBuilder)
 {
     loaderBuilder.AddInterfaceImplementation(typeof(IFactoryLoader));
     loaderBuilder.DefineDefaultConstructor(MethodAttributes.Public);
     var methodIl = loaderBuilder.DefineMethod("CreateFactory", MethodAttributes.Public | MethodAttributes.Virtual,
         typeof(object), factoryContructorParameters).GetILGenerator();
     methodIl.Emit(OpCodes.Ldarg_1);
     methodIl.Emit(OpCodes.Newobj, factoryConstructorBuilder);
     methodIl.Emit(OpCodes.Ret);
 }
Example #10
0
        public void EmitConstrucorIL(ConstructorBuilder builder)
        {
            ConstructorInfo conObj = typeof(object).GetConstructor(new Type[0]);

            //call constructor of base object
            ILGenerator il = builder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, conObj);
            il.Emit(OpCodes.Ret);
        }
        private static void DefineParameterNames(
            ConstructorBuilder constructor, 
            ConstructorMetadata constructorMetadata)
        {
            for (var i = 0; i < constructorMetadata.Parameters.Length; i++)
            {
                var parameter = constructorMetadata.Parameters[i];

                constructor.DefineParameter(parameter.Sequence, ParameterAttributes.None, parameter.Name);
            }
        }
Example #12
0
	static void EmitCtor (TypeBuilder genericFoo) {
		ConstructorBuilder mb = genericFoo.DefineConstructor (MethodAttributes.Public, CallingConventions.Standard, null);
		ILGenerator il = mb.GetILGenerator ();
		for (int i = 0; i < 20; ++i)
				il.Emit (OpCodes.Nop);

		il.Emit (OpCodes.Ldarg_0);
		il.Emit (OpCodes.Call, typeof (object).GetConstructors()[0]);
		il.Emit (OpCodes.Ret);

		ctor = mb;
	}
Example #13
0
        public void Execute()
        {
            constructorBuilder = builder().TypeBuilder.DefineConstructor(
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.RTSpecialName,
                CallingConventions.Standard,
                this.types().ToArray());

            int counter = 1;
            foreach(Type type in this.types())
            {
                constructorBuilder.DefineParameter(counter, ParameterAttributes.None, type.Name + "_" + counter);
                counter++;
            }
        }
 protected ILGenerator GetInitConstructorIL(ConstructorBuilder constructorBuilder, Dictionary<TypeFactoryMap, FieldBuilder> singletonFields)
 {
     var constrIl = constructorBuilder.GetILGenerator();
     constrIl.Emit(OpCodes.Ldarg_0);
     constrIl.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
     foreach (var fieldPair in singletonFields)
     {
         var injectableGetSingletonMethod = typeof(IInjectableModule).GetMethod("GetSingleton").MakeGenericMethod(fieldPair.Key.BaseType);
         constrIl.Emit(OpCodes.Ldarg_0);
         constrIl.Emit(OpCodes.Ldarg_1);
         constrIl.Emit(OpCodes.Ldstr, fieldPair.Key.Name);
         constrIl.Emit(OpCodes.Callvirt, injectableGetSingletonMethod);
         constrIl.Emit(OpCodes.Stfld, fieldPair.Value);
     }
     return constrIl;
 }
        public ConstructorBuilder DefineConstructorBuilder()
        {
            if (IsConstructor)
            {
                ConstructorBuilder = Parent.TypeBuilder.DefineConstructor(
                    GetMethodModifiers(),
                    CallingConventions.Standard,
                    GetArgumentTypes());
            }
            else
            {
                ConstructorBuilder = Parent.TypeBuilder.DefineTypeInitializer();
            }

            return ConstructorBuilder;
        }
		internal ConstructorEmitter(AbstractTypeEmitter maintype, params ArgumentReference[] arguments)
		{
			this.maintype = maintype;

			var args = ArgumentsUtil.InitializeAndConvert(arguments);

			builder = maintype.TypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, args);
			// if we don't copy the parameter attributes, the default binder will fail
			// when trying to resolve constructors from the passed argument values.
            for (int i = 0; i < args.Length; ++i)
            {
                var arg = arguments[i];
                var paramBuilder = builder.DefineParameter(i + 1, arg.ParameterAttributes, "");
                if (arg.DefaultValue != DBNull.Value)
                    paramBuilder.SetConstant(arg.DefaultValue);
            }
		}
        public void Execute()
        {
            constructorBuilder = builder().TypeBuilder.DefineConstructor(
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.RTSpecialName,
                CallingConventions.Standard,
                new Type[0]);

            this.constructor = typeof(object).GetConstructor(new Type[0]);

            ILGenerator il = constructorBuilder.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, constructor);
            il.Emit(OpCodes.Ret);
        }
        public Type CreateContextType(List <Table> tables)
        {
            Type        PocoType;
            TypeBuilder PocoTypeBuilder;

            //TypeBuilder ClassTypeBuilder;

            Types.Clear();
            TypeBuilders.Clear();

            //Context
            ContextTypeBuilder = DynamicTypeBuilder.GetTypeBuilder("Context", typeof(DbContextBase));

            //Context Constructor
            System.Reflection.Emit.ConstructorBuilder constructor = ContextTypeBuilder.DefineDefaultConstructor(System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.SpecialName | System.Reflection.MethodAttributes.RTSpecialName);

            //Create Normal Poco Type to be used as a reference
            foreach (Table table in tables)
            {
                TypeBuilders.Add(table.VariableName, CreatePocoTypeBuilder(table));
            }


            //Navigation properties
            foreach (Table table in tables)
            {
                CreateNavigationProperties(table);
            }


            //Creates DbSet Propeties for the Context
            foreach (Table ti in tables)
            {
                PocoTypeBuilder = TypeBuilders[ti.VariableName];
                PocoType        = PocoTypeBuilder.CreateType();
                Types.Add(ti.VariableName, PocoType);
                DynamicTypeBuilder.CreateProperty(ContextTypeBuilder, ti.VariableName, typeof(DbSet <>).MakeGenericType(new Type[] { PocoType }), false);
            }


            Type type = ContextTypeBuilder.CreateType();


            return(type);
        }
Example #19
0
        public void TestContainsAccessorAttributeWithDifferentOverload()
        {
            AssemblyName an = new AssemblyName();

            an.Name = "DynamicRandomAssembly";
            AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);

            ModuleBuilder mb = TestLibrary.Utilities.GetModuleBuilder(ab, "Module1");

            TypeBuilder tb = mb.DefineType("DynamicRandomClass", TypeAttributes.Public);

            Type[] parameterTypes = { typeof(int), typeof(double) };

            System.Reflection.Emit.ConstructorBuilder cb =
                tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameterTypes);

            Assert.Contains("Public", cb.Attributes.ToString());
        }
 public ASMCompileContext()
     : base(null)
 {
     this.FunctionList = new List<_FncInfo>();
     AssemblyName aName = new AssemblyName("DynamicAssemblyExample");
     this.ab = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);
     this.mb = this.ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
     this.tb = this.mb.DefineType("MyDynamicType", TypeAttributes.Public, typeof(JSGlobalContext));
     this.fncListField = this.tb.DefineField("fnclist", typeof(JSDebugFunctionDef[]), FieldAttributes.Static | FieldAttributes.Private);
     this.ctor1 = this.tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, Type.EmptyTypes);
     ILGenerator ctor1IL = this.ctor1.GetILGenerator();
     ctor1IL.Emit(OpCodes.Ldarg_0);
     ctor1IL.Emit(OpCodes.Call, typeof(object).GetConstructor(Type.EmptyTypes));
     ctor1IL.Emit(OpCodes.Ret);
     this.GlobalMethod = this.tb.DefineMethod("GlobalCode", MethodAttributes.Static | MethodAttributes.Public, typeof(JSValue), new Type[] { typeof(JSContext) });
     this.GlobalMethod.DefineParameter(1, ParameterAttributes.None, "context");
     base.fncData = new CompileContext.LocalFunctionData(this.GlobalMethod.GetILGenerator());
 }
Example #21
0
        /// <summary>
        /// Creates a ConstructorBuilder for current constructor entity.
        /// </summary>
        public override void PrepareSelf()
        {
            // todo: remove when we support static ctors
            if(IsStatic)
                throw new LensCompilerException(CompilerMessages.ConstructorStatic);

            if (ConstructorBuilder != null || IsImported)
                return;

            var ctx = ContainerType.Context;

            if (ArgumentTypes == null)
                ArgumentTypes = Arguments == null
                    ? new Type[0]
                    : Arguments.Values.Select(fa => fa.GetArgumentType(ctx)).ToArray();

            ConstructorBuilder = ContainerType.TypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, ArgumentTypes);
            Generator = ConstructorBuilder.GetILGenerator(Context.ILStreamSize);
        }
 private void EmitCtor(PropertyAndField[] properties, ConstructorBuilder method)
 {
     ILGenerator iLGenerator = method.GetILGenerator();
     iLGenerator.Emit(OpCodes.Ldarg_0);
     iLGenerator.Emit(OpCodes.Call, ObjectType.GetConstructor(Type.EmptyTypes));
     int index = 0;
     if (0 < properties.Length)
     {
         do
         {
             iLGenerator.Emit(OpCodes.Ldarg_0);
             int arg = index + 1;
             iLGenerator.Emit(OpCodes.Ldarg, arg);
             iLGenerator.Emit(OpCodes.Stfld, properties[index].Field);
             index = arg;
         }
         while (index < properties.Length);
     }
     iLGenerator.Emit(OpCodes.Ret);
 }
        protected internal override void OnCompile()
        {
            Builder = this.TargetClass.Builder.DefineConstructor(this.Attributes
                , this.CallingConvention, this.ParameterTypes
                );
            ILGenerator il = SetILGenerator(Builder.GetILGenerator());
            try
            {
                CompileParameters(Builder);
                CompileLocals(il);

                ILHelper msil = new ILHelper(il);
                base.EmitInstructions(msil);
                msil.Return();
            }
            finally
            {
                SetILGenerator(il);
            }
        }
Example #24
0
		static TypeBuilder DefineDelegate () {
		   TypeBuilder typeBuilder = module.DefineType( "MyDelegate", 
				TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Sealed, 
				typeof (object) );
			args = typeBuilder.DefineGenericParameters ("TIn", "TOut");

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

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

			invoke_mb = typeBuilder.DefineMethod( 
				"Invoke", 
				MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, 
				args [1], 
				new Type[] { args [0] } ); 

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

			MethodBuilder mb = typeBuilder.DefineMethod( 
				"BeginInvoke", 
				MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, 
				typeof (IAsyncResult), 
				new Type[] { args [0], typeof (AsyncCallback), typeof (object) } ); 

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

			mb = typeBuilder.DefineMethod( 
				"EndInvoke", 
				MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig, 
				args [1], 
				new Type[] {  typeof (IAsyncResult) } ); 

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

			return typeBuilder;
		}
		void SetUp (AssemblyBuilderAccess access)
		{
			AssemblyName assemblyName = new AssemblyName ();
			assemblyName.Name = ASSEMBLY_NAME;

			assembly = AppDomain.CurrentDomain.DefineDynamicAssembly (
				assemblyName, access,
				Path.GetTempPath ());

			module = assembly.DefineDynamicModule ("module1");

			tb = module.DefineType ("Bar");
			GenericTypeParameterBuilder [] typeParams = tb.DefineGenericParameters ("T");

			cb = tb.DefineConstructor (MethodAttributes.Public,
				CallingConventions.Standard,
				new Type [] { typeof (string), typeof (int) });
			ILGenerator ig = cb.GetILGenerator ();
			ig.Emit (OpCodes.Ret);

			typeBarOfInt32 = tb.MakeGenericType (typeof (int));
			ci = TypeBuilder.GetConstructor (typeBarOfInt32, cb);
		}
Example #26
0
        [System.Security.SecurityCritical]  // auto-generated
        private ConstructorBuilder DefineTypeInitializerNoLock()
        {
            ThrowIfCreated();

            // change the attributes and the class constructor's name
            MethodAttributes attr = MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName;

            ConstructorBuilder constBuilder = new ConstructorBuilder(
                ConstructorInfo.TypeConstructorName, attr, CallingConventions.Standard, null, m_module, this);

            return constBuilder;
        }
Example #27
0
		public ConstructorBuilder DefineConstructor (MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
		{
			check_not_created ();
			ConstructorBuilder cb = new ConstructorBuilder (this, attributes,
				callingConvention, parameterTypes, requiredCustomModifiers,
				optionalCustomModifiers);
			if (ctors != null) {
				ConstructorBuilder[] new_ctors = new ConstructorBuilder [ctors.Length+1];
				System.Array.Copy (ctors, new_ctors, ctors.Length);
				new_ctors [ctors.Length] = cb;
				ctors = new_ctors;
			} else {
				ctors = new ConstructorBuilder [1];
				ctors [0] = cb;
			}
			return cb;
		}
 private void NegTestCaseVerificationHelper(
     ConstructorBuilder constructor,
     int sequence,
     ParameterAttributes attribute,
     string paramName,
     Type desiredException)
 {
     Assert.Throws(desiredException, () => { constructor.DefineParameter(sequence, attribute, paramName); });
 }
        public Type CreateContextType(List <Table> tables, string cString)
        {
            Types.Clear();
            TypeBuilders.Clear();

            _logger.LogTrace("Start building runtime DynamicDbContext");

            //Context
            ContextTypeBuilder = _typeBuilder.GetTypeBuilder("DynamicDbContext", typeof(DbContextBase));

            //Context Constructor
            System.Reflection.Emit.ConstructorBuilder constructor = ContextTypeBuilder.DefineDefaultConstructor(
                System.Reflection.MethodAttributes.Public |
                System.Reflection.MethodAttributes.SpecialName |
                System.Reflection.MethodAttributes.RTSpecialName);

            //Create Normal Poco Type to be used as a reference
            foreach (Table table in tables)
            {
                TypeBuilders.Add(table.VariableName, CreatePocoTypeBuilder(table));
            }

            _logger.LogTrace("Start building navigation properties");

            //Navigation properties
            foreach (Table table in tables)
            {
                CreateNavigationProperties(table);
            }

            _logger.LogTrace("Start building Dbset for each table");

            //Creates DbSet Properties for the Context
            foreach (Table ti in tables)
            {
                var pocoTypeBuilder = TypeBuilders[ti.VariableName];
                var pocoType        = pocoTypeBuilder.CreateType();
                Types.Add(ti.VariableName, pocoType);

                _typeBuilder.CreateProperty(ContextTypeBuilder, ti.VariableName,
                                            typeof(DbSet <>).MakeGenericType(new Type[] { pocoType }), false);
            }

            _logger.LogTrace("Start building OnConfiguring override method.");

            // context OnConfiguring method override.
            var onConfiguringMethod = ContextTypeBuilder.OverrideOnConfiguring(cString);

            ContextTypeBuilder.DefineMethodOverride(onConfiguringMethod,
                                                    typeof(DbContext).GetMethod("OnConfiguring", BindingFlags.Instance | BindingFlags.NonPublic));

            Type type = ContextTypeBuilder.CreateType();

            if (_config.SaveLibraryRunTime)
            {
                _logger.LogTrace("Try saving the created DbContext into the disk.");

                _typeBuilder.SaveTypeBuilder(ContextTypeBuilder, "DynamicDataStore");
            }

            _logger.LogTrace("Done building Dynamic DbContext.");

            return(type);
        }
Example #30
0
 public ConstructorBuilder(System.Reflection.Emit.ConstructorBuilder builder)
 {
     _builder = builder;
     IL       = builder.GetILGenerator();
 }
Example #31
0
        [System.Security.SecurityCritical]  // auto-generated
        private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention, 
            Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers)
        {
            CheckContext(parameterTypes);
            CheckContext(requiredCustomModifiers);
            CheckContext(optionalCustomModifiers);

            ThrowIfCreated();

            String name;

            if ((attributes & MethodAttributes.Static) == 0)
            {
                name = ConstructorInfo.ConstructorName;
            }
            else
            {
                name = ConstructorInfo.TypeConstructorName;
            }

            attributes = attributes | MethodAttributes.SpecialName;

            ConstructorBuilder constBuilder = 
                new ConstructorBuilder(name, attributes, callingConvention, 
                    parameterTypes, requiredCustomModifiers, optionalCustomModifiers, m_module, this);

            m_constructorCount++;

            return constBuilder;
        }
        private void GenerateStaticGet(TypeBuilder t, ConstructorBuilder ctor)
        {
            MethodBuilder mb = t.DefineMethod("Get",
                MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig,
                ctor.DeclaringType, new Type[] { typeof(Int32) });

            ILGenerator gen = mb.GetILGenerator();
            Label l1 = gen.DefineLabel();
            gen.DeclareLocal(ctor.DeclaringType);
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Ldarg_0);
            gen.Emit(OpCodes.Newobj, ctor);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, l1);
            gen.MarkLabel(l1);
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);
        }
        private void GenerateStaticGetList(TypeBuilder t, ConstructorBuilder ctor)
        {
            Type tt = ctor.DeclaringType.MakeArrayType();

            MethodInfo mi = typeof(DalUtility).GetMethod("GetList",
                BindingFlags.Static |
                BindingFlags.Public);
            MethodInfo genericMi = mi.MakeGenericMethod(new Type[] { ctor.DeclaringType });

            MethodBuilder mb = t.DefineMethod("GetList",
                MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig,
                tt, Type.EmptyTypes);
            ILGenerator gen = mb.GetILGenerator();
            gen.DeclareLocal(tt);
            Label l1 = gen.DefineLabel();
            gen.Emit(OpCodes.Nop);
            gen.Emit(OpCodes.Call, genericMi);
            gen.Emit(OpCodes.Stloc_0);
            gen.Emit(OpCodes.Br_S, l1);
            gen.MarkLabel(l1);
            gen.Emit(OpCodes.Ldloc_0);
            gen.Emit(OpCodes.Ret);
        }
Example #34
0
		/// <summary>
		/// Creates a new <see cref="ILEmitter"/> for a given <see cref="ConstructorBuilder"/>.
		/// </summary>
		/// <param name="constructorBuilder">The <see cref="ConstructorBuilder"/> to emit to.</param>
		public ILEmitter(ConstructorBuilder/*!*/ constructorBuilder)
			: this(constructorBuilder.GetILGenerator(), Containers.ConstructorBuilder)
		{
			this.method = constructorBuilder;
		}
Example #35
0
        /// <summary>
        /// Generate the declaration for the IgnoresAccessChecksToAttribute type.
        /// This attribute will be both defined and used in the dynamic assembly.
        /// Each usage identifies the name of the assembly containing non-public
        /// types the dynamic assembly needs to access.  Normally those types
        /// would be inaccessible, but this attribute allows them to be visible.
        /// It works like a reverse InternalsVisibleToAttribute.
        /// This method returns the ConstructorInfo of the generated attribute.
        /// </summary>
        public static ConstructorInfo AddToModule(ModuleBuilder mb)
        {
            TypeBuilder attributeTypeBuilder =
                mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute",
                              TypeAttributes.Public | TypeAttributes.Class,
                              typeof(Attribute));

            // Create backing field as:
            // private string assemblyName;
            FieldBuilder assemblyNameField =
                attributeTypeBuilder.DefineField("assemblyName", typeof(string), FieldAttributes.Private);

            // Create ctor as:
            // public IgnoresAccessChecksToAttribute(string)
            ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public,
                                                                                           CallingConventions.HasThis,
                                                                                           new Type[] { assemblyNameField.FieldType });

            ILGenerator il = constructorBuilder.GetILGenerator();

            // Create ctor body as:
            // this.assemblyName = {ctor parameter 0}
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg, 1);
            il.Emit(OpCodes.Stfld, assemblyNameField);

            // return
            il.Emit(OpCodes.Ret);

            // Define property as:
            // public string AssemblyName {get { return this.assemblyName; } }
            _ = attributeTypeBuilder.DefineProperty(
                "AssemblyName",
                PropertyAttributes.None,
                CallingConventions.HasThis,
                returnType: typeof(string),
                parameterTypes: null);

            MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod(
                "get_AssemblyName",
                MethodAttributes.Public,
                CallingConventions.HasThis,
                returnType: typeof(string),
                parameterTypes: null);

            // Generate body:
            // return this.assemblyName;
            il = getterMethodBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, assemblyNameField);
            il.Emit(OpCodes.Ret);

            // Generate the AttributeUsage attribute for this attribute type:
            // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
            TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo();

            // Find the ctor that takes only AttributeTargets
            ConstructorInfo attributeUsageConstructorInfo =
                attributeUsageTypeInfo.DeclaredConstructors
                .Single(c => c.GetParameters().Length == 1 &&
                        c.GetParameters()[0].ParameterType == typeof(AttributeTargets));

            // Find the property to set AllowMultiple
            PropertyInfo allowMultipleProperty =
                attributeUsageTypeInfo.DeclaredProperties
                .Single(f => string.Equals(f.Name, "AllowMultiple"));

            // Create a builder to construct the instance via the ctor and property
            CustomAttributeBuilder customAttributeBuilder =
                new CustomAttributeBuilder(attributeUsageConstructorInfo,
                                           new object[] { AttributeTargets.Assembly },
                                           new PropertyInfo[] { allowMultipleProperty },
                                           new object[] { true });

            // Attach this attribute instance to the newly defined attribute type
            attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder);

            // Make the TypeInfo real so the constructor can be used.
            return(attributeTypeBuilder.CreateTypeInfo() !.DeclaredConstructors.Single());
        }