Пример #1
0
        public void TestValidDataWithMultipleParameters()
        {
            int i = 0;

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

            for (i = 1; i < _supportedAttributes.Length; ++i)
            {
                ConstructorBuilder constructor = CreateConstructorBuilder("PosTest1_Type" + i,
                                                                          parameterTypes);

                constructor.DefineParameter(1, _supportedAttributes[i - 1], "parameter1" + i);
                constructor.DefineParameter(2, _supportedAttributes[i], "parameter2" + i);

                ILGenerator ilg = constructor.GetILGenerator();
                ilg.Emit(OpCodes.Ldarg_0);
                ilg.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[] { }));
                ilg.Emit(OpCodes.Ret);

                _typeBuilder.CreateTypeInfo().AsType();
                ParameterInfo[] definedParams = constructor.GetParameters();

                Assert.Equal(2, definedParams.Length);
            }
        }
Пример #2
0
        /// <summary>
        /// Generates the (<see cref="ScriptContext"/>, <see cref="DTypeDesc"/>) constructor.
        /// </summary>
        /// <param name="typeBuilder">The type builder.</param>
        /// <param name="shortConstructor">This type's short constructor.</param>
        /// <returns>The constructor builder.</returns>
        /// <remarks>
        /// The entire constructor is generated. See <see cref="PHP.Core.PhpObject(PHP.Core.ScriptContext,DTypeDesc)"/>.
        /// </remarks>
        public static ConstructorBuilder GenerateLongConstructor(TypeBuilder typeBuilder, ConstructorInfo shortConstructor)
        {
            ConstructorBuilder ctor_builder = typeBuilder.DefineConstructor(LongConstructorAttributes,
                                                                            CallingConventions.Standard, LongConstructorParamTypes);

            // annotate with EditorBrowsable attribute
#if !SILVERLIGHT // Not available on Silverlight
            ctor_builder.SetCustomAttribute(AttributeBuilders.EditorBrowsableNever);
#endif

            // define parameter names
            ctor_builder.DefineParameter(1, ParameterAttributes.None, "context");
            ctor_builder.DefineParameter(2, ParameterAttributes.None, "caller");

            // call this type's short constructor
            ILEmitter il = new ILEmitter(ctor_builder);
            il.Ldarg(FunctionBuilder.ArgThis);
            il.Ldarg(FunctionBuilder.ArgContextInstance);
            il.LdcI4(1);
            il.Emit(OpCodes.Call, shortConstructor);

            // call PhpObject.InvokeConstructor
            il.Ldarg(FunctionBuilder.ArgThis);
            il.Ldarg(1);
            il.Ldarg(2);
            il.Emit(OpCodes.Call, Methods.DObject_InvokeConstructor);

            il.Emit(OpCodes.Ret);

            return(ctor_builder);
        }
        private void AddConstructor()
        {
            Type[] paramTypes = Sequence.Collect(typeToIntercept, typeof(Type)).ToArray();

            ConstructorBuilder ctorBuilder = typeBuilder.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.HasThis,
                paramTypes);

            ctorBuilder.DefineParameter(1, ParameterAttributes.None, "target");
            ctorBuilder.DefineParameter(2, ParameterAttributes.None, "typeToProxy");
            ILGenerator il = ctorBuilder.GetILGenerator();

            // Call base class constructor

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, ObjectMethods.Constructor);

            // Initialize pipeline field
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Newobj, InterceptionBehaviorPipelineMethods.Constructor);
            il.Emit(OpCodes.Stfld, proxyInterceptionPipelineField);

            // Initialize the target field
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Stfld, targetField);

            // Initialize the typeToProxy field
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Stfld, typeToProxyField);

            il.Emit(OpCodes.Ret);
        }
        public void DefineParameter_NoParameters_InvalidSequence_ThrowsArgumentOutOfRangeException()
        {
            TypeBuilder        type        = Helpers.DynamicType(TypeAttributes.NotPublic);
            ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[0]);

            Assert.Throws <ArgumentOutOfRangeException>(() => constructor.DefineParameter(-1, ParameterAttributes.None, "p"));
            Assert.Throws <ArgumentOutOfRangeException>(() => constructor.DefineParameter(1, ParameterAttributes.None, "p"));
        }
Пример #5
0
 void DefineParameterNames(string[] parameterNames)
 {
     for (var i = 0; i < parameterNames.Length; i++)
     {
         _constructor.DefineParameter(i + 1, ParameterAttributes.None, parameterNames[i]);
     }
 }
Пример #6
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);
        }
Пример #7
0
        private static void GenerateCustomConstructor(TypeBuilder tb, Type funcType, ParameterInfo parameterInfo, FieldBuilder fb)
        {
            Type            objType = typeof(object);
            ConstructorInfo objCtor = objType.GetConstructor(new Type[0]);

            Type[]             ctorParams = new Type[] { funcType };
            ConstructorBuilder customCtor = tb.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                ctorParams);

            var paramBuilder    = customCtor.DefineParameter(1, parameterInfo.Attributes, "func");
            var paramAttributes = parameterInfo.CustomAttributes;

            foreach (var attr in paramAttributes)
            {
                var targetAttrBuilder = GetAttributeBuilder(attr.AttributeType);
                paramBuilder.SetCustomAttribute(targetAttrBuilder);
            }

            ILGenerator ctorIlg = customCtor.GetILGenerator();

            ctorIlg.Emit(OpCodes.Ldarg_0);
            ctorIlg.Emit(OpCodes.Call, objCtor);
            ctorIlg.Emit(OpCodes.Ldarg_0);
            ctorIlg.Emit(OpCodes.Ldarg_1);

            // store the ctor arg in the _func field
            ctorIlg.Emit(OpCodes.Stfld, fb);

            ctorIlg.Emit(OpCodes.Ret);
        }
Пример #8
0
        protected static ConstructorBuilder CreateConstructor(TypeBuilder typeBuilder, List <FieldBuilder> fieldBuilders)
        {
            List <Type>        types = fieldBuilders.Select(s => s.FieldType).ToList();
            ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                fieldBuilders.Select(s => s.FieldType).ToArray());

            for (int i = 0; i < fieldBuilders.Count; i++)
            {
                constructorBuilder.DefineParameter(i + 1, ParameterAttributes.None, fieldBuilders[i].Name);
            }

            ILGenerator constructorIlGenerator = constructorBuilder.GetILGenerator();

            constructorIlGenerator.CallBaseTypeDefaultConstructor(typeBuilder.BaseType);
            constructorIlGenerator.Emit(OpCodes.Nop);
            if (fieldBuilders.Count > 0)
            {
                for (int i = 0; i < fieldBuilders.Count; i++)
                {
                    constructorIlGenerator.Emit(OpCodes.Ldarg_0);
                    constructorIlGenerator.Emit(OpCodes.Ldarg_S, (i + 1));
                    constructorIlGenerator.Emit(OpCodes.Stfld, fieldBuilders[i]);
                }
            }
            constructorIlGenerator.Emit(OpCodes.Ret);
            return(constructorBuilder);
        }
Пример #9
0
        private static void DefineParameters(this ConstructorBuilder constructorBuilder, ConstructorInfo constructorInfo, IEnumerable <string> additionalParameterNames)
        {
            var position = 1;

            foreach (var additionalParameterName in additionalParameterNames)
            {
                constructorBuilder.DefineParameter(position++, ParameterAttributes.None, additionalParameterName);
            }

            var parameterInfos = constructorInfo.GetParameters();

            foreach (var parameterInfo in parameterInfos)
            {
                constructorBuilder.DefineParameter(parameterInfo.Position + position, parameterInfo.Attributes, parameterInfo.Name);
            }
        }
Пример #10
0
        private void AddConstructor(ConstructorInfo ctor)
        {
            if (!ctor.IsPublic && !ctor.IsFamily && !ctor.IsFamilyOrAssembly)
            {
                return;
            }
            MethodAttributes attributes = (ctor.Attributes & ~(MethodAttributes.RTSpecialName | MethodAttributes.HasSecurity | MethodAttributes.RequireSecObject) & ~MethodAttributes.MemberAccessMask) | MethodAttributes.Public;

            ParameterInfo[] parameters = ctor.GetParameters();
            Type[]          paramTypes = (from item in parameters
                                          select item.ParameterType).ToArray();
            ConstructorBuilder ctorBuilder = _typeBuilder.DefineConstructor(attributes, ctor.CallingConvention, paramTypes);

            for (int j = 0; j < parameters.Length; j++)
            {
                ctorBuilder.DefineParameter(j + 1, parameters[j].Attributes, parameters[j].Name);
            }
            ILGenerator il = ctorBuilder.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            for (int i = 0; i < paramTypes.Length; i++)
            {
                il.Emit(OpCodes.Ldarg, i + 1);
            }
            il.Emit(OpCodes.Call, ctor);
            il.Emit(OpCodes.Ret);
        }
 private static void DefineParameters(this ConstructorBuilder constructorBuilder, params ParameterInfo[] parameters)
 {
     foreach (var parameterInfo in parameters)
     {
         constructorBuilder.DefineParameter(parameterInfo.Position + 1, parameterInfo.Attributes, parameterInfo.Name);
     }
 }
        /// <summary>
        /// Defines the special IgnoresAccessChecksToAttribute type in the <see cref="moduleBuilder"/>.
        /// </summary>
        /// <returns>The generated attribute type.</returns>
        private TypeInfo EmitMagicAttribute()
        {
            TypeBuilder tb = this.moduleBuilder.DefineType(
                "System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute",
                TypeAttributes.NotPublic,
                typeof(Attribute));

            var attributeUsage = new CustomAttributeBuilder(
                AttributeUsageCtor,
                new object[] { AttributeTargets.Assembly },
                new PropertyInfo[] { AttributeUsageAllowMultipleProperty },
                new object[] { false });

            tb.SetCustomAttribute(attributeUsage);

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

            cb.DefineParameter(1, ParameterAttributes.None, "assemblyName");

            ILGenerator il = cb.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, AttributeBaseClassCtor);
            il.Emit(OpCodes.Ret);

            return(tb.CreateTypeInfo());
        }
Пример #13
0
        /// <summary>
        /// 发行。
        /// </summary>
        public void Emit(ConstructorBuilder builder)
        {
#if NET40
            var attributes = builder.GetMethodImplementationFlags();
#else
            var attributes = builder.MethodImplementationFlags;
#endif

            if ((attributes & MethodImplAttributes.Runtime) != MethodImplAttributes.IL)
            {
                return;
            }

            if (IsEmpty)
            {
                InvokeBaseConstructor();
            }

            foreach (var item in parameters)
            {
                item.Emit(builder.DefineParameter(item.Position, item.Attributes, item.ParameterName));
            }

            var ilg = builder.GetILGenerator();

            base.Load(ilg);

            ilg.Emit(OpCodes.Ret);
        }
Пример #14
0
        private static FieldInfo MakeConstructor(TypeBuilder typeBuilder, Type baseType)
        {
            FieldBuilder    fieldBuilder = typeBuilder.DefineField("proxiedObj", baseType, FieldAttributes.Private | FieldAttributes.InitOnly);
            ConstructorInfo constructor  = baseType.GetConstructor(Type.EmptyTypes);

            if (constructor == null)
            {
                throw new Exception("Proxed object don't have constructor with no parameter");
            }
            ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new Type[] { baseType });

            constructorBuilder.DefineParameter(1, ParameterAttributes.None, "proxiedObj");
            ILGenerator lGenerator = constructorBuilder.GetILGenerator();
            Label       label      = lGenerator.DefineLabel();

            lGenerator.Emit(OpCodes.Ldarg_0);
            lGenerator.Emit(OpCodes.Call, constructor);
            lGenerator.Emit(OpCodes.Ldarg_1);
            lGenerator.Emit(OpCodes.Brtrue_S, label);
            lGenerator.Emit(OpCodes.Ldstr, "proxiedObj");
            ConstructorInfo constructorInfo = typeof(ArgumentNullException).GetConstructor(new Type[] { typeof(string) });

            if (constructorInfo != null)
            {
                lGenerator.Emit(OpCodes.Newobj, constructorInfo);
                lGenerator.Emit(OpCodes.Throw);
            }
            lGenerator.MarkLabel(label);
            lGenerator.Emit(OpCodes.Ldarg_0);
            lGenerator.Emit(OpCodes.Ldarg_1);
            lGenerator.Emit(OpCodes.Stfld, fieldBuilder);
            lGenerator.Emit(OpCodes.Ret);
            return(fieldBuilder);
        }
Пример #15
0
        // TODO: use in Python's OverrideConstructor:
        public static ParameterBuilder DefineParameterCopy(ConstructorBuilder builder, int paramIndex, ParameterInfo info)
        {
            var result = builder.DefineParameter(1 + paramIndex, info.Attributes, info.Name);

            CopyParameterAttributes(info, result);
            return(result);
        }
        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);
        }
Пример #17
0
        public void GenerateName(bool isStatic)
        {
            MethodAttributes attr = getMethodAttributes(isStatic);

            if (FnName.IsConstructor(this.ClassName) != -1)
            {
                List <Type>        argTypes           = FnName.ProcDesc.GetArgTypes(1);
                var                ClassSymbol        = MethodContext.ClassContext.ClassSymbol;
                ConstructorBuilder constructorBuilder = ClassSymbol.ClassBuilder.DefineConstructor(attr, CallingConventions.Standard, argTypes.ToArray());
                MethodContext.EmitContext.SetBuilder(constructorBuilder);
                MethodContext.EmitContext.ClassContext = this.ClassContext.EmitContext;
                if (FnName.IsMinConstructor())
                {
                    MethodContext.ClassContext.ZeroConstructor = constructorBuilder;
                }
                else
                {
                    List <TKTProcArg> normalArgs = this.MethodContext.ProcDesc.GetSpecialArgs(1);
                    int start_i = isStatic ? 0 : 1;
                    for (var i = 0; i < normalArgs.Count; i++)
                    {
                        constructorBuilder.DefineParameter(i + start_i, ParameterAttributes.None, normalArgs[i].ArgName);
                    }
                }
                MethodContext.ClassContext.ConstructorBuilderList.Add(constructorBuilder);
            }
            else
            {
                List <Type> argTypes    = FnName.ProcDesc.GetArgTypes(1);
                var         ClassSymbol = MethodContext.ClassContext.ClassSymbol;
                MethodName = getMethodName(isStatic);
                MethodBuilder methodBuilder = ClassSymbol.ClassBuilder.DefineMethod(MethodName, attr, MethodContext.RetType, argTypes.ToArray());
                if (MethodName == "启动")
                {
                    Type                   myType           = typeof(STAThreadAttribute);
                    ConstructorInfo        infoConstructor  = myType.GetConstructor(new Type[] { });
                    CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(infoConstructor, new object[] { });
                    methodBuilder.SetCustomAttribute(attributeBuilder);
                }
                else
                {
                    setAttrMappingCode(methodBuilder);
                }
                MethodContext.EmitContext.SetBuilder(methodBuilder);
                MethodContext.EmitContext.ClassContext = this.ClassContext.EmitContext;
                List <TKTProcArg> genericArgs = this.MethodContext.ProcDesc.GetSpecialArgs(2);
                if (genericArgs.Count > 0)
                {
                    string[] names = genericArgs.Select(p => p.ArgName).ToArray();
                    methodBuilder.DefineGenericParameters(names);
                }

                List <TKTProcArg> normalArgs = this.MethodContext.ProcDesc.GetSpecialArgs(1);
                int start_i = isStatic ? 0 : 1;
                for (var i = 0; i < normalArgs.Count; i++)
                {
                    methodBuilder.DefineParameter(i + start_i, ParameterAttributes.None, normalArgs[i].ArgName);
                }
            }
        }
Пример #18
0
        public void EmitName()
        {
            var classBuilder = this.ProcContext.ClassContext.EmitContext.ClassBuilder;
            MethodAttributes   methodAttributes;
            CallingConventions callingConventions;
            bool isSstatic = (this.ProcContext.IsStatic);

            if (isSstatic)
            {
                methodAttributes   = MethodAttributes.Private | MethodAttributes.Static;
                callingConventions = CallingConventions.Standard;
            }
            else
            {
                methodAttributes   = MethodAttributes.Public | MethodAttributes.Virtual;
                callingConventions = CallingConventions.HasThis;
            }
            var argTypes = this.constructorDesc.GetArgTypes();
            ConstructorBuilder constructorBuilder = classBuilder.DefineConstructor(methodAttributes, callingConventions, argTypes);

            ProcContext.EmitContext.SetBuilder(constructorBuilder);
            ProcContext.EmitContext.ILout = constructorBuilder.GetILGenerator();

            List <ZMethodNormalArg> normalArgs = this.constructorDesc.Args;
            int start_i = isSstatic ? 0 : 1;

            for (var i = 0; i < normalArgs.Count; i++)
            {
                constructorBuilder.DefineParameter(i + start_i, ParameterAttributes.None, normalArgs[i].ArgName);
            }
        }
Пример #19
0
        public override void EmitName()
        {
            var                classBuilder = this.ConstructorContext.ClassContext.GetTypeBuilder();
            bool               isStatic     = this.ConstructorContext.IsStatic();
            MethodAttributes   methodAttributes;
            CallingConventions callingConventions;

            if (isStatic)
            {
                methodAttributes   = MethodAttributes.Private | MethodAttributes.Static;
                callingConventions = CallingConventions.Standard;
            }
            else
            {
                methodAttributes   = MethodAttributes.Public;
                callingConventions = CallingConventions.HasThis;
            }
            var argTypes = this.ConstructorContext.ZConstructorInfo.GetParameterTypes();// this.constructorDesc.GetParamTypes();
            ConstructorBuilder constructorBuilder = classBuilder.DefineConstructor(methodAttributes, callingConventions, argTypes);

            ConstructorContext.SetBuilder(constructorBuilder);

            var normalArgs = this.ConstructorContext.ZConstructorInfo.GetNormalParameters();
            int start_i    = isStatic ? 0 : 1;

            for (var i = 0; i < normalArgs.Length; i++)
            {
                constructorBuilder.DefineParameter(i + start_i, ParameterAttributes.None, normalArgs[i].GetZParamName());
            }
        }
        private static void CreateConstructor <T>(TypeBuilder typeBuilder)
        {
            ConstructorInfo parentCtor = (typeof(T)).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).SingleOrDefault();

            if (parentCtor != null)
            {
                ParameterInfo[]    parentCtorParms = parentCtor.GetParameters();
                ConstructorBuilder ctor            = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, parentCtorParms.Select(p => p.ParameterType).ToArray());

                for (int idx = 0; idx < parentCtorParms.Length; idx++)
                {
                    ctor.DefineParameter(idx + 1, ParameterAttributes.None, parentCtorParms[idx].Name);
                }

                ILGenerator ilGenerator = ctor.GetILGenerator();

                ilGenerator.Emit(OpCodes.Ldarg_0);
                for (int i = 1; i <= parentCtorParms.Count(); i++)
                {
                    ilGenerator.Emit(OpCodes.Ldarg, i);
                }
                ilGenerator.Emit(OpCodes.Call, parentCtor);
                ilGenerator.Emit(OpCodes.Ret);
            }
        }
Пример #21
0
        /// <summary>adds a constructor to a type, setting the attributes on the parameters</summary>
        /// <remarks>forgeign method: should be better on TypeBuilder, but not possible</remarks>
        /// <returns>the ConstructorBuilder for the method created</returns>
        public ConstructorBuilder AddConstructor(TypeBuilder builder, ParameterSpec[] parameters,
                                                 MethodAttributes attrs)
        {
            Type[] paramTypes = new Type[parameters.Length];
            for (int i = 0; i < parameters.Length; i++)
            {
                paramTypes[i] = parameters[i].GetParamTypeMergedDirection();
            }

            ConstructorBuilder constrBuild =
                builder.DefineConstructor(attrs, CallingConventions.Standard,
                                          paramTypes);

            // define the paramter-names / attributes
            for (int i = 0; i < parameters.Length; i++)
            {
                ParameterAttributes paramAttr  = ParameterAttributes.None;
                ParameterBuilder    paramBuild =
                    constrBuild.DefineParameter(i + 1, paramAttr,
                                                parameters[i].GetPramName());
                // custom attribute spec
                TypeContainer specType = parameters[i].GetParamType();
                for (int j = 0; j < specType.GetSeparatedAttrs().Length; j++)
                {
                    paramBuild.SetCustomAttribute(specType.GetSeparatedAttrs()[j]);
                }
            }

            return(constrBuild);
        }
        public void DefineParameter_ZeroSequence_SingleParameter()
        {
            TypeBuilder        type        = Helpers.DynamicType(TypeAttributes.NotPublic);
            ConstructorBuilder constructor = type.DefineConstructor(MethodAttributes.Public, CallingConventions.Any, new Type[0]);

            Assert.NotNull(constructor.DefineParameter(0, ParameterAttributes.None, "p"));
        }
        private static ILGenerator CreateConstructorIlGenerator(TypeBuilder typeBuilder)
        {
            ConstructorBuilder constructorBuilder = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, new[] { typeof(ICustomTypeBiserializerRegistry) });

            constructorBuilder.DefineParameter(1, ParameterAttributes.None, "biserializerRegistry");

            return(constructorBuilder.GetILGenerator());
        }
        public IParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string strParamName)
        {
            // Parameter name may be null.

            var parameterBuilder = _constructorBuilder.DefineParameter(iSequence, attributes, strParamName);

            return(new ParameterBuilderAdapter(parameterBuilder));
        }
Пример #25
0
        private void InitConstuctor()
        {
            ConstructorBuilder ctor              = _typeBuilder.DefineConstructor(MethodAttributes.Public | MethodAttributes.HideBySig, CallingConventions.HasThis, new Type[] { _modelParam.Type, _formatProviderParam.Type });
            ParameterBuilder   modelArg          = ctor.DefineParameter(1, ParameterAttributes.None, "model");
            ParameterBuilder   formatProviderArg = ctor.DefineParameter(2, ParameterAttributes.None, "formatProvider");
            ILGenerator        il = ctor.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Call, CTOR_Object);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Stfld, _modelParam.Field);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_2);
            il.Emit(OpCodes.Stfld, _formatProviderParam.Field);
            il.Emit(OpCodes.Ret);
        }
Пример #26
0
        static Type createDelegate(TypeBuilder tbDelegates, MethodInfo method)
        {
            // Initially based on this: https://blogs.msdn.microsoft.com/joelpob/2004/02/15/creating-delegate-types-via-reflection-emit/

            // Create the delegate type
            TypeAttributes ta = TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.Sealed | TypeAttributes.NestedPublic;
            TypeBuilder    tb = tbDelegates.DefineNestedType(method.Name, ta, typeof(MulticastDelegate));
            // Apply [UnmanagedFunctionPointer] using the value from RuntimeClass.defaultCallingConvention
            CustomAttributeBuilder cab = new CustomAttributeBuilder(ciFPAttribute, new object[1] {
                RuntimeClass.defaultCallingConvention
            });

            tb.SetCustomAttribute(cab);

            // Create constructor for the delegate
            MethodAttributes   ma = MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig | MethodAttributes.Public;
            ConstructorBuilder cb = tb.DefineConstructor(ma, CallingConventions.Standard, new Type[] { typeof(object), typeof(IntPtr) });

            cb.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
            cb.DefineParameter(1, ParameterAttributes.In, "object");
            cb.DefineParameter(2, ParameterAttributes.In, "method");

            // Create Invoke method for the delegate. Appending one more parameter to the start, `[in] IntPtr pThis`
            ParameterInfo[] methodParams = method.GetParameters();
            Type[]          paramTypes   = new Type[methodParams.Length + 1];
            paramTypes[0] = typeof(IntPtr);
            for (int i = 0; i < methodParams.Length; i++)
            {
                ParameterInfo  pi = methodParams[i];
                Type           tp = pi.ParameterType;
                iCustomMarshal cm = pi.customMarshaller();
                if (null != cm)
                {
                    tp = cm.getNativeType(pi);
                }
                paramTypes[i + 1] = tp;
            }

            var mb = tb.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, typeof(int), paramTypes);

            mb.SetImplementationFlags(MethodImplAttributes.Runtime | MethodImplAttributes.Managed);
            defineDelegateParameters(mb, methodParams);
            // The method has no code, it's pure virtual.

            return(tb.CreateType());
        }
Пример #27
0
        public static void Main()
        {
            AssemblyName assemblyName = new AssemblyName();

            assemblyName.Name    = "Utilities";
            assemblyName.Version = new Version("1.0.1.0");

            AssemblyBuilder assembly = Thread.GetDomain().
                                       DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);

            ModuleBuilder module;

            module = assembly.DefineDynamicModule("MainModule", "Utilities.dll");

            TypeBuilder utilsTypeBldr = module.DefineType("Apress.ExpertDotNet.EmitClass.Utilities",
                                                          TypeAttributes.Class | TypeAttributes.Public, typeof(System.Object));

            FieldBuilder nameFld = utilsTypeBldr.DefineField("a", typeof(string),
                                                             FieldAttributes.PrivateScope);

            MethodBuilder toStringMethod = utilsTypeBldr.DefineMethod("ToString",
                                                                      MethodAttributes.Public | MethodAttributes.Virtual, typeof(string),
                                                                      null);

            ILGenerator toStringIL = toStringMethod.GetILGenerator();

            toStringIL.Emit(OpCodes.Ldarg_0);
            toStringIL.Emit(OpCodes.Ldfld, nameFld);
            toStringIL.Emit(OpCodes.Ret);

            Type[]          constructorParamList = { typeof(string) };
            ConstructorInfo objectConstructor    = (typeof(System.Object)).
                                                   GetConstructor(new Type[0]);
            ConstructorBuilder constructor = utilsTypeBldr.DefineConstructor(
                MethodAttributes.Public, CallingConventions.Standard,
                constructorParamList);

            constructor.DefineParameter(1, ParameterAttributes.None, "name");
            ILGenerator constructorIL = constructor.GetILGenerator();

            constructorIL.Emit(OpCodes.Ldarg_0);
            constructorIL.Emit(OpCodes.Call, objectConstructor);
            constructorIL.Emit(OpCodes.Ldarg_0);
            constructorIL.Emit(OpCodes.Ldarg_1);
            constructorIL.Emit(OpCodes.Stfld, nameFld);
            constructorIL.Emit(OpCodes.Ret);

            Type   utilsType = utilsTypeBldr.CreateType();
            object utils     = Activator.CreateInstance(utilsType, new object[] {
                "New Object!"
            });
            object name = utilsType.InvokeMember("ToString",
                                                 BindingFlags.InvokeMethod, null, utils, null);

            Console.WriteLine("ToString() returned: " + (string)name);

            assembly.Save("Utilities.dll");
        }
Пример #28
0
        private static void AddNameParameters(IEnumerable <string> parameterNames, ConstructorBuilder constructor)
        {
            var i = 1;

            foreach (var parameterName in parameterNames)
            {
                constructor.DefineParameter(i++, ParameterAttributes.None, parameterName);
            }
        }
Пример #29
0
 private void NegTestCaseVerificationHelper(
     ConstructorBuilder constructor,
     int sequence,
     ParameterAttributes attribute,
     string paramName,
     Type desiredException)
 {
     Assert.Throws(desiredException, () => { constructor.DefineParameter(sequence, attribute, paramName); });
 }
Пример #30
0
        private static void DefineParameters(this ConstructorBuilder constructorBuilder, IEnumerable <string> parameterNames)
        {
            var position = 1;

            foreach (var parameterName in parameterNames)
            {
                constructorBuilder.DefineParameter(position++, ParameterAttributes.None, parameterName);
            }
        }
Пример #31
0
		public virtual void ApplyAttributes (MethodBuilder mb, ConstructorBuilder cb, int index, PredefinedAttributes pa)
		{
			if (builder != null)
				throw new InternalErrorException ("builder already exists");

			var pattrs = ParametersCompiled.GetParameterAttribute (modFlags);
			if (HasOptionalExpression)
				pattrs |= ParameterAttributes.Optional;

			if (mb == null)
				builder = cb.DefineParameter (index, pattrs, Name);
			else
				builder = mb.DefineParameter (index, pattrs, Name);

			if (OptAttributes != null)
				OptAttributes.Emit ();

			if (HasDefaultValue) {
				//
				// Emit constant values for true constants only, the other
				// constant-like expressions will rely on default value expression
				//
				var def_value = DefaultValue;
				Constant c = def_value != null ? def_value.Child as Constant : default_expr as Constant;
				if (c != null) {
					if (c.Type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
						pa.DecimalConstant.EmitAttribute (builder, (decimal) c.GetValue (), c.Location);
					} else {
						builder.SetConstant (c.GetValue ());
					}
				} else if (default_expr.Type.IsStruct) {
					//
					// Handles special case where default expression is used with value-type
					//
					// void Foo (S s = default (S)) {}
					//
					builder.SetConstant (null);
				}
			}

			if (parameter_type != null) {
				if (parameter_type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
					pa.Dynamic.EmitAttribute (builder);
				} else if (parameter_type.HasDynamicElement) {
					pa.Dynamic.EmitAttribute (builder, parameter_type, Location);
				}
			}
		}