DefineConstructor() public method

public DefineConstructor ( System attributes, System callingConvention, System parameterTypes ) : System.Reflection.Emit.ConstructorBuilder
attributes System
callingConvention System
parameterTypes System
return System.Reflection.Emit.ConstructorBuilder
Ejemplo n.º 1
0
 /// <summary>
 /// Adds a new public constructor to the class, with the given parameters.
 /// </summary>
 /// <param name="parameterTypes">The types of the parameters of the method.</param>
 /// <returns>The defined constructor.</returns>
 public ConstructorBuilderHelper DefinePublicConstructor(params Type[] parameterTypes)
 {
     return(new ConstructorBuilderHelper(
                this,
                _typeBuilder.DefineConstructor(
                    MethodAttributes.Public, CallingConventions.Standard, parameterTypes)));
 }
Ejemplo n.º 2
0
        public ClassBuilder(TypeBuilder tb)
        {
            this.tb = tb;
            System.Type[] param = {};

            ConstructorBuilder ctor = tb.DefineConstructor( MethodAttributes.Public, CallingConventions.Standard, param );
            cil = ctor.GetILGenerator();

            ctor = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, param);
            ccil = ctor.GetILGenerator();
        }
        private static void BuildConstructor(TypeBuilder proxyBuilder, Type proxyType,
			 FieldBuilder wrappedType, FieldBuilder invokeHandlers, TypeDebugging debug)
        {
            var arguments = new Type[] { proxyType, typeof(IInvocationHandler[]) };
            var constructor = proxyBuilder.DefineConstructor(
                MethodAttributes.Public | MethodAttributes.SpecialName |
                MethodAttributes.RTSpecialName | MethodAttributes.HideBySig,
                CallingConventions.Standard, arguments);

            using (var generator = debug.GetMethodDebugging(constructor))
            {
                //  Call the base constructor.
                generator.Emit(OpCodes.Ldarg_0);
                var objectCtor = proxyType.GetConstructor(Type.EmptyTypes);
                generator.Emit(OpCodes.Call, objectCtor);
                //  Store the target object.
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldarg_1);
                generator.Emit(OpCodes.Stfld, wrappedType);
                //  Store the handlers.
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldarg_2);
                generator.Emit(OpCodes.Stfld, invokeHandlers);
                generator.Emit(OpCodes.Ret);
            }
        }
Ejemplo n.º 4
0
 protected ConstructorInfo GrabConstructor(ConstructorInfo Original, TypeBuilder On)
 {
     if(Original == null) return null;
     
     if(ConstructorsDone.ContainsKey(Original))
         return ConstructorsDone[Original];
     
     if(!Sources.Contains(Original.Module))
         return ConstructorReplaceGenerics(Original);
     
     if(On == null)
         On = GrabType(Original.DeclaringType) as TypeBuilder;
     
     ConstructorBuilder Builder = On.DefineConstructor(Original.Attributes, 
         Original.CallingConvention, ParameterTypes(Original));
     
     Builder.SetImplementationFlags(Original.GetMethodImplementationFlags());
     
     if(ConstructorsDone.ContainsKey(Original))
         return ConstructorsDone[Original];
     
     ConstructorsDone.Add(Original, Builder);
     
     CopyMethodBody(Original, Builder);
     
     return Builder;
 }
Ejemplo n.º 5
0
        private static void CreateConstructor(TypeBuilder tb, IList<IInjectableConstructorArg> properties)
        {
            var constructor = tb.DefineConstructor(
                MethodAttributes.Public |
                MethodAttributes.SpecialName |
                MethodAttributes.RTSpecialName,
                CallingConventions.Standard,
                properties.Select(p => p.PropertyType).ToArray());

            var conObj = typeof(object).GetConstructor(new Type[0]);

            ILGenerator il = constructor.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, conObj);
            il.Emit(OpCodes.Nop);
            il.Emit(OpCodes.Nop);

            for (var i = 0; i < properties.Count; i++)
            {
                var property = properties[i];

                il.Emit(OpCodes.Ldarg_0);
                il.Emit(OpCodes.Ldarg, i + 1);
                il.Emit(OpCodes.Call, property.Setter);
                il.Emit(OpCodes.Nop);
            }

            il.Emit(OpCodes.Nop);
            il.Emit(OpCodes.Ret);
        }
Ejemplo n.º 6
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.º 7
0
        public BFMemory(TypeBuilder typeBuilder)
        {
            PointerFieldBuilder = typeBuilder.DefineField("pointer", typeof(short), FieldAttributes.Static | FieldAttributes.Private);
            MemoryFieldBuilder = typeBuilder.DefineField("memory", typeof(byte[]), FieldAttributes.Static | FieldAttributes.Private);

            var staticConstructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Static,CallingConventions.Standard, null);
            GenerateStaticConstructorBody(staticConstructorBuilder.GetILGenerator());
        }
 /// <summary>
 /// Defines the constructor used.
 /// </summary>
 /// <param name="owner"></param>
 /// <param name="interfaceType"></param>
 /// <returns></returns>
 protected override ConstructorBuilder DefineConstructor(TypeBuilder owner, Type interfaceType)
 {
     var probeType = typeof(IMethodCallProbe<>).MakeGenericType(interfaceType);
     return owner.DefineConstructor(
         MethodAttributes.Public,
         CallingConventions.Standard,
         new[] { typeof(ILibrary), probeType });
 }
 public ConstructorBuilder GenerateConstructor(TypeBuilder builder, Type[] parameters)
 {
     return builder.DefineConstructor(
         MethodAttributes.Public |
         MethodAttributes.SpecialName |
         MethodAttributes.RTSpecialName,
         CallingConventions.Standard,
         parameters);
 }
Ejemplo n.º 10
0
		CodeMethod (CodeClass cls, MethodAttributes attributes, Type[] parameterTypes) 
		{
			this.cls = cls;
			this.typeBuilder = cls.TypeBuilder;
			this.attributes = attributes;
			this.parameterTypes = parameterTypes;
			this.name = typeBuilder.Name;
		
			methodBase = typeBuilder.DefineConstructor (attributes, CallingConventions.Standard, parameterTypes);
			builder = new CodeBuilder (cls);
		}
Ejemplo n.º 11
0
 private static ConstructorInfo BuildConstructor(TypeBuilder type, FieldInfo helperClassFieldInfo)
 {
     // Declaring method builder
     // Method attributes
     ConstructorBuilder method = type.DefineConstructor(MethodAttributes.Public, 0, new[] { typeof(IDbConnection) });
     // Preparing Reflection instances
     ConstructorInfo ctor1 = typeof(DebuggerNonUserCodeAttribute).GetConstructor(
         BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
         null,
         new Type[]{
     },
         null
         );
     ConstructorInfo ctor2 = typeof(DataContextBase).GetConstructor(
         BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
         null,
         new Type[]{
     typeof(IDbConnection)
     },
         null
         );
     ConstructorInfo ctor3 = typeof(SqlDataContextHelperClass).GetConstructor(
         BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
         null,
         new Type[]{
     typeof(DataContext)
     },
         null
         );
     FieldInfo field4 = helperClassFieldInfo;
     // Adding custom attributes to method
     // [DebuggerNonUserCodeAttribute]
     method.SetCustomAttribute(
         new CustomAttributeBuilder(
             ctor1,
             new Type[] { }
             )
         );
     // Parameter connection
     //ParameterBuilder connection = method.DefineParameter(0, ParameterAttributes.None, "connection");
     ILGenerator gen = method.GetILGenerator();
     // Writing body
     gen.Emit(OpCodes.Ldarg_0);
     gen.Emit(OpCodes.Ldarg_1);
     gen.Emit(OpCodes.Call, ctor2);
     gen.Emit(OpCodes.Ldarg_0);
     gen.Emit(OpCodes.Ldarg_0);
     gen.Emit(OpCodes.Newobj, ctor3);
     gen.Emit(OpCodes.Stfld, field4);
     gen.Emit(OpCodes.Ret);
     // finished
     return method;
 }
Ejemplo n.º 12
0
 private void Constructor(TypeBuilder typeBuilder)
 {
     var constructor = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.RTSpecialName, CallingConventions.Standard, new[] { typeof(IDynamicImplementation) });
     var constructorILGenerator = constructor.GetILGenerator();
     constructorILGenerator.Emit(OpCodes.Ldarg_0);
     var originalConstructor = typeof(Object).GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, new Type[0], null);
     constructorILGenerator.Emit(OpCodes.Call, originalConstructor);
     constructorILGenerator.Emit(OpCodes.Ldarg_0);
     constructorILGenerator.Emit(OpCodes.Ldarg_1);
     constructorILGenerator.Emit(OpCodes.Stfld, __interceptionService);
     constructorILGenerator.Emit(OpCodes.Ret);
 }
Ejemplo n.º 13
0
        /// <summary>
        ///   AddConstructor
        /// </summary>
        /// <param name="typeBuilder"></param>
        /// <param name="backingFields"></param>
        private static void CreateConstructor(System.Reflection.Emit.TypeBuilder typeBuilder, IReadOnlyList <dynamic> backingFields)
        {
            #region Constructor

            //--------------------------------------------------------------------

            // Constructor:  (Default)
            // <code>
            //  .custom instance void [Newtonsoft.Json]Newtonsoft.Json.JsonConverterAttribute::.ctor(class [mscorlib]System.Type) = { type(<NameSpace>.PayloadComplexTypeConverter) }
            //   .method public hidebysig specialname rtspecialname instance void .ctor() cil managed
            //  {
            //  }
            // </code>

            // Attribute:
            // [JsonConverter(typeof(PayloadComplexTypeConverter))]
            // Ctor attributes

            /* Uncomment if needing similar functionality for nested duck types */
            // Attribute:
            // [JsonConverterAttribute()]
            //var jsonConverterAttr = typeof(JsonConverterAttribute).GetConstructor(new [] { typeof(Type) });
            //if (jsonConverterAttr != null) {
            //  // ReSharper disable once InconsistentNaming
            //  var jsonConverterCABuilder = new CustomAttributeBuilder(
            //    jsonConverterAttr,
            //    new object[] { typeof(PayloadComplexTypeConverter) }
            //  );
            //  typeBuilder.SetCustomAttribute(jsonConverterCABuilder);
            //}

            var constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, CallingConventions.Standard, new[] { typeof(string), typeof(string), typeof(Dictionary <string, Type>) });
            var ctorIl             = constructorBuilder.GetILGenerator();

            // Now, we'll load the current instance ref in arg 0, along
            // with the value of parameter "x" stored in arg X, into stfld.

            for (var x = 0; x < backingFields.Count; x++)
            {
                ctorIl.Emit(OpCodes.Ldarg_0);
                ctorIl.Emit(OpCodes.Ldarg_S, x + 1);
                ctorIl.Emit(OpCodes.Stfld, backingFields[x]);
            }

            // Our work complete, we return.

            ctorIl.Emit(OpCodes.Ret);

            //--------------------------------------------------------------------

            #endregion Constructor
        }
Ejemplo n.º 14
0
        private static void GenerateConstructor(TypeBuilder typeBuilder)
        {
            var constructor = typeBuilder.DefineConstructor(
                 MethodAttributes.Public | MethodAttributes.SpecialName |
                 MethodAttributes.RTSpecialName,
                 CallingConventions.Standard, Type.EmptyTypes);

            var constructorMethod = typeof(object).GetConstructor(Type.EmptyTypes);
            var constructorGenerator = constructor.GetILGenerator();

            constructorGenerator.Emit(OpCodes.Ldarg_0);
            constructorGenerator.Emit(OpCodes.Call, constructorMethod);
            constructorGenerator.Emit(OpCodes.Ret);
        }
Ejemplo n.º 15
0
        private void WeaveConstructor(TypeBuilder typeBuilder, EventBrokerResolvedType eventBrokerResolvedType)
        {
            ConstructorBuilder ctor = null;
            ILGenerator ilGenerator = null;
            var ctorArgs = new[] { eventBrokerResolvedType.DecalringType, typeof(EventInfo), eventBrokerResolvedType.EventBrokerInvokeDelegateType };
            var baseCtor = eventBrokerResolvedType.EventBrokerBaseClassType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, ctorArgs, null);

            ctor = typeBuilder.DefineConstructor(ctorAttrs, CallingConventions.Standard | CallingConventions.HasThis, ctorArgs);
            ilGenerator = ctor.GetILGenerator();
            ilGenerator.EmitLoadArg(0);
            ctorArgs.ForEach(1, (arg, i) => ilGenerator.EmitLoadArg(i));
            ilGenerator.Emit(OpCodes.Call, baseCtor);
            ilGenerator.Emit(OpCodes.Ret);
        }
        public void Build(TypeBuilder typeBuilder, Type contractType)
        {
            ConstructorBuilder constructor = typeBuilder.DefineConstructor(
                MethodAttributes.Public, CallingConventions.HasThis, new[] { contractType, typeof(IPointcut[]) });

            ILGenerator il = constructor.GetILGenerator();

            // call base constructor passing second parameter of this constructor as argument
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Call, typeof(InvocationProxy).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).First());

            il.Emit(OpCodes.Ret);
        }
Ejemplo n.º 17
0
 private static void DefineForwardingConstructor(TypeBuilder definingType, Type baseType, Type[] parameters, Type[] baseParams, string[] paramNames, Action<ILGenerator> paramIL)
 {
     ConstructorBuilder builder = definingType.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameters);
     int num = 0;
     foreach (string str in paramNames)
     {
         builder.DefineParameter(++num, ParameterAttributes.None, str);
     }
     ILGenerator iLGenerator = builder.GetILGenerator();
     iLGenerator.Emit(OpCodes.Ldarg_0);
     paramIL(iLGenerator);
     ConstructorInfo constructor = baseType.GetConstructor(baseParams);
     iLGenerator.Emit(OpCodes.Call, constructor);
     iLGenerator.Emit(OpCodes.Ret);
 }
        private static void BuildParameterlessConstructor(TypeBuilder proxyBuilder, Type proxyType,
			TypeDebugging debug)
        {
            var constructor = proxyBuilder.DefineConstructor(
                MethodAttributes.Private | MethodAttributes.SpecialName |
                MethodAttributes.RTSpecialName | MethodAttributes.HideBySig,
                CallingConventions.Standard, Type.EmptyTypes);

            using (var generator = debug.GetMethodDebugging(constructor))
            {
                generator.Emit(OpCodes.Ldarg_0);
                var objectCtor = proxyType.GetConstructor(Type.EmptyTypes);
                generator.Emit(OpCodes.Call, objectCtor);
                generator.Emit(OpCodes.Ret);
            }
        }
Ejemplo n.º 19
0
        public static void DefineCtor(TypeBuilder typeBuilder, FieldBuilder fieldBuilder)
        {
            var parameterTypes = new Type[] { fieldBuilder.FieldType };
            ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameterTypes);
            ILGenerator il = ctorBuilder.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Stfld, fieldBuilder);
            il.Emit(OpCodes.Ret);

            MethodBuilder createBuider = typeBuilder.DefineMethod("<Create>", MethodAttributes.Static | MethodAttributes.Public, typeBuilder, parameterTypes);
            il = createBuider.GetILGenerator();
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Newobj, ctorBuilder);
            il.Emit(OpCodes.Ret);
        }
Ejemplo n.º 20
0
		private static ILGenerator Generate_Constructor(TypeBuilder tb, FieldSet fields)
		{
			var cb = tb.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { typeof(string) });
			var ilgen = cb.GetILGenerator();
			ilgen.PushContext(new ILContext(fields));

			// --- DECLARE PARAMETERS ---
			ilgen.DeclareParameter("filename");
			// --- DECLARE LOCALS ---
			ilgen.DeclareLocal<TextReader>("tr");
			ilgen.DeclareLocal<string>("quote");

			ilgen.EmitCallToBaseConstructor();                                  // base();

			ilgen.ConstructVariable<ArrayList>("_quotes");                      // _quotes = new ArrayList();
			ilgen.ConstructVariable<Random>("_random");                         // _random = new Random();

			ilgen.EmitLoadVariable("filename");                                 // "filename" - first constructor parameter
			ilgen.EmitCall(typeof(File), "OpenText");                           // invoke File.OpenText with "filename" parameter
			ilgen.EmitStoreVariable("tr");

			// Mark the loop label
			ilgen.EmitLoop((gen, exit) =>
			{
				gen.EmitLoadVariable("tr");                                     // load local "tr"
				gen.EmitCallvirt<TextReader>("ReadLine");                       // call tr.ReadLine() (virtual)
				gen.EmitStoreVariable("quote");                                 // store the result in the local "quote"

				gen.EmitLoadVariable("quote");                                  // load the local "quote"
				gen.Emit(OpCodes.Brfalse_S, exit);                              // branch to the exit label if "quote" is null

				gen.EmitLoadVariable("_quotes");                                // load "_quotes" field
				gen.EmitLoadVariable("quote");                                  // load local "quote"
				gen.EmitCallvirt<ArrayList, object>("Add");                     // call _quotes.Add(object) (virtual)
				gen.Emit(OpCodes.Pop);                                          // pop the result of _quotes.Add(object) (unused)
			});

			ilgen.EmitLoadVariable("tr");                                       // load local "tr"
			ilgen.EmitCallvirt<TextReader>("Close");                            // call tr.Close() (virtual)

			ilgen.Emit(OpCodes.Ret);                                            // emit return opcode
			ilgen.PopContext();

			return ilgen;
		}
        private void CreateConstructor(TypeBuilder typeBuilder)
        {
            var ctor = SnapshotBaseType.GetConstructors(BindingFlags.Public | BindingFlags.Instance).First();
            var ctorSignature = ctor.GetParameters().Select(p => p.ParameterType);

            var ctorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctorSignature.ToArray());
            var il = ctorBuilder.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0); // push this

            int paramIndex = 1;
            foreach (var param in ctorSignature) // push all constructor parameters onto the stack
            {
                il.Emit(OpCodes.Ldarg, paramIndex++);
            }

            il.Emit(OpCodes.Call, ctor); // call DynamicSnapshotBase constructor
            il.Emit(OpCodes.Ret); // return
        }
Ejemplo n.º 22
0
        private void BuildConstructor(ConstructorInfo constructor, TypeBuilder typeBuilder)
        {
            ParameterInfo[] parameterInfos = constructor.GetParameters();
            Type[] parameterTypes = new Type[parameterInfos.Length ];

            //copy super ctor param types
            for (int i = 0; i < parameterInfos.Length; i++)
            {
                parameterTypes[i] = parameterInfos[i].ParameterType;
            }

            ConstructorBuilder proxyConstructor = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parameterTypes);
            ILGenerator il = proxyConstructor.GetILGenerator();
            for (int i = 0; i < parameterTypes.Length + 1 /* also load "this" */; i++)
            {
                il.Emit(OpCodes.Ldarg, i);
            }
            il.Emit(OpCodes.Callvirt, constructor);

            il.Emit(OpCodes.Ret);
        }
Ejemplo n.º 23
0
        // generates this constructor:
        // public NewType(param0, param1, ...) : base(param0, param1, ...) { }
        private static void ImplementConstructor(TypeBuilder newType, ConstructorInfo baseCtor) {
            ParameterInfo[] parameters = baseCtor.GetParameters();
            Type[] parameterTypes = (from p in parameters select p.ParameterType).ToArray();

            ConstructorBuilder newCtor = newType.DefineConstructor(
                (baseCtor.Attributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public /* force public constructor */,
                baseCtor.CallingConvention, parameterTypes);

            // parameter 0 is 'this', so we start at index 1
            for (int i = 0; i < parameters.Length; i++) {
                newCtor.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name);
            }

            // load all arguments (including 'this') in proper order, then call and return
            ILGenerator ilGen = newCtor.GetILGenerator();
            for (int i = 0; i <= parameterTypes.Length; i++) {
                ilGen.Emit(OpCodes.Ldarg_S, (byte)i);
            }
            ilGen.Emit(OpCodes.Call, baseCtor);
            ilGen.Emit(OpCodes.Ret);
        }
Ejemplo n.º 24
0
        private static void ImplementConstructor(TypeBuilder newType, ConstructorInfo baseConstructor)
        {
            var parameters = baseConstructor.GetParameters();
            var parameterTypes = parameters.Select(p => p.ParameterType).ToArray();

            var constructor = newType.DefineConstructor(MethodAttributes.Public, baseConstructor.CallingConvention, parameterTypes);

            // parameter 0 is 'this', so we start at index 1
            for (int i = 0; i < parameters.Length; i++)
            {
                constructor.DefineParameter(i + 1, parameters[i].Attributes, parameters[i].Name);
            }

            var ilGenerator = constructor.GetILGenerator();
            for (int i = 0; i <= parameterTypes.Length; i++)
            {
                ilGenerator.Emit(OpCodes.Ldarg_S, (byte)i);
            }

            ilGenerator.Emit(OpCodes.Call, baseConstructor);
            ilGenerator.Emit(OpCodes.Ret);
        }
Ejemplo n.º 25
0
        private static void ImplementConstructor(TypeBuilder newType, ConstructorInfo baseCtor)
        {
            ParameterInfo[] parameters = baseCtor.GetParameters();
            Type[] parameterTypes = new Type[parameters.Length];
            for (int idx = 0; idx < parameters.Length; idx++)
                parameterTypes[idx] = parameters[idx].ParameterType;

            ConstructorBuilder newCtor = newType.DefineConstructor(
                (baseCtor.Attributes & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public /* force public constructor */,
                baseCtor.CallingConvention, parameterTypes);

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

            ILGenerator ilGen = newCtor.GetILGenerator();

            for (int i = 0; i <= parameterTypes.Length; i++)
                ilGen.Emit(OpCodes.Ldarg_S, (byte)i);

            ilGen.Emit(OpCodes.Call, baseCtor);
            ilGen.Emit(OpCodes.Ret);
        }
Ejemplo n.º 26
0
		public void DefineContextType()
		{
			linqContextBuilder = cg.IL.TypeBuilder.DefineNestedType(ContextTypeName + cg.IL.GetNextUniqueIndex(),
				TypeAttributes.Class | TypeAttributes.NestedPrivate | TypeAttributes.Sealed,
				typeof(PHP.Core.LinqContext), null);

			// .ctor:

			ConstructorBuilder ctor = linqContextBuilder.DefineConstructor(MethodAttributes.Assembly,
				CallingConventions.HasThis, Types.LinqContextArgs);

			ILEmitter il = new ILEmitter(ctor);
			il.Ldarg(0);
			il.Ldarg(1);
			il.Ldarg(2);
			il.Ldarg(3);
			il.Ldarg(4);
			il.Emit(OpCodes.Call, Constructors.LinqContext);
			il.Emit(OpCodes.Ret);

			linqContextCtor = ctor;
		}
        public DataServiceContextGenerator(Uri serviceRoot)
        {
            AssemblyName myAsmName = new AssemblyName("DynamicAssembly" + Guid.NewGuid().ToString());

            AssemblyBuilder myAsmBuilder = Thread.GetDomain().DefineDynamicAssembly(myAsmName,
                                                            AssemblyBuilderAccess.Run);
            // Generate a single-module assembly.
            _moduleBuilder =
                myAsmBuilder.DefineDynamicModule(myAsmName.Name);
            _contextTypeBuilder = _moduleBuilder.DefineType("MyDataContext",
                                                            TypeAttributes.Public,
                                                            typeof(MyDataServiceContext));
            ConstructorBuilder ctorBuilder = _contextTypeBuilder.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                null);
            ILGenerator ctorIL = ctorBuilder.GetILGenerator();
            ctorIL.Emit(OpCodes.Ldarg_0);
            ctorIL.Emit(OpCodes.Ldstr, serviceRoot.AbsoluteUri);
            ctorIL.Emit(OpCodes.Newobj, typeof(Uri).GetConstructor(new[] { typeof(string) }));
            ctorIL.Emit(OpCodes.Call, typeof(MyDataServiceContext).GetConstructors().First());
            ctorIL.Emit(OpCodes.Ret);
        }
        private static void AddParentConstructor(TypeBuilder typeBuilder, Type parentType)
        {
            var parentConstructor = parentType.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance | BindingFlags.Instance).First();
            var parentParameters = parentConstructor.GetParameters();

            var parameterTypes = parentParameters.Select(x => x.ParameterType).ToArray();
            var constructorBuilder = typeBuilder.DefineConstructor(parentConstructor.Attributes | MethodAttributes.Public, parentConstructor.CallingConvention, parameterTypes);
            var generator = constructorBuilder.GetILGenerator();

            // load 'this' pointer
            generator.Emit(OpCodes.Ldarg_0);

            for (var i = 1; i <= parentParameters.Length; i++)
            {
                var parentParameter = parentParameters[i - 1];
                constructorBuilder.DefineParameter(i, parentParameter.Attributes, parentParameter.Name);

                generator.Emit(OpCodes.Ldarg_S, i);
            }

            generator.Emit(OpCodes.Call, parentConstructor);
            generator.Emit(OpCodes.Ret);
        }
		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);
		}
Ejemplo n.º 30
0
        public static void ImplementIn(this ConstructorInfo constructorInfo, TypeBuilder proxy)
        {
            var arguments = constructorInfo.GetParameters();
            var types = arguments.Select(arg => arg.GetType()).ToArray();

            var constructor = proxy.DefineConstructor(MethodAttributes.Public, constructorInfo.CallingConvention, types);

            for (var index = 0; index < arguments.Length; index++)
            {
                var argument = arguments[index];
                constructor.DefineParameter(index, argument.Attributes, argument.Name);
            }

            var generator = constructor.GetILGenerator();

            for (var index = 0; index <= types.Length; index++)
            {
                //                generator.Emit(OpCodes.Ldarg_S, (byte)index);
                generator.Emit(OpCodes.Ldarg_S, index);
            }

            generator.Emit(OpCodes.Call, constructorInfo);
            generator.Emit(OpCodes.Ret);
        }
Ejemplo n.º 31
0
    private static void AddConstructor(TypeBuilder typeBuilder, Type serviceInterface, FieldInfo proxyField, Type baseType) {
      var constructorBuilder = typeBuilder.DefineConstructor(
                                                             MethodAttributes.Public | MethodAttributes.HideBySig |
                                                             MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
                                                             CallingConventions.HasThis,
                                                             new[] {
                                                               serviceInterface
                                                             });

      // Generate the constructor IL. 

      var gen = constructorBuilder.GetILGenerator();

      // The constructor calls the base constructor with the string[] parameter.

      gen.Emit(OpCodes.Ldarg_0);
      gen.Emit(OpCodes.Call, baseType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder, Type.EmptyTypes, null));

      gen.Emit(OpCodes.Ldarg_0);
      gen.Emit(OpCodes.Ldarg_1);
      gen.Emit(OpCodes.Stfld, proxyField);

      gen.Emit(OpCodes.Ret);
    }
Ejemplo n.º 32
0
        private static void GenerateConstructor(
            TypeBuilder typeBuilder, 
            TypeMetadata typeMetadata,
            ConstructorMetadata constructorMetadata,
            FieldMetadataFieldBuilderMap fieldBuilders)
        {
            var constructor = typeBuilder.DefineConstructor(
                constructorMetadata.MethodAttributes,
                CallingConventions.Standard,
                constructorMetadata.ParameterTypes);

            DefineParameterNames(constructor, constructorMetadata);

            var il = constructor.GetILGenerator();

            InitializeInstanceFields(il, typeMetadata, constructorMetadata, fieldBuilders);

            if (constructorMetadata.CallBaseConstructor)
            {
                GenerateBaseConstructorCall(il, constructorMetadata);
            }

            il.Emit(OpCodes.Ret);
        }
Ejemplo n.º 33
0
 public static ConstructorBuilder DefineConstructor(this TypeBuilder tb, MethodAttributes attributes, CallingConventions callingConventions, GenericTypeParameterBuilder[] parameterTypes)
 {
     return(tb.DefineConstructor(attributes, callingConventions, parameterTypes.Select(g => g.AsType()).ToArray()));
 }
Ejemplo n.º 34
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());
        }