DefineDynamicModule() public method

public DefineDynamicModule ( string name ) : System.Reflection.Emit.ModuleBuilder
name string
return System.Reflection.Emit.ModuleBuilder
Beispiel #1
0
		public AssemblyEmitter( string assemblyName, bool canSave )
		{
			m_AssemblyName = assemblyName;

			m_AppDomain = AppDomain.CurrentDomain;

			m_AssemblyBuilder = m_AppDomain.DefineDynamicAssembly(
				new AssemblyName( assemblyName ),
				canSave ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run
			);

			if ( canSave )
			{
				m_ModuleBuilder = m_AssemblyBuilder.DefineDynamicModule(
					assemblyName,
					String.Format( "{0}.dll", assemblyName.ToLower() ),
					false
				);
			}
			else
			{
				m_ModuleBuilder = m_AssemblyBuilder.DefineDynamicModule(
					assemblyName,
					false
				);
			}
		}
		public ModuleBuilder DefineDynamicModule(AssemblyBuilder assemblyBuilder, string moduleName)
		{
#if DEBUG
			ModuleBuilder moduleBuilder =
				assemblyBuilder.DefineDynamicModule(moduleName, string.Format("{0}.mod", moduleName), true);
#else
			ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule(moduleName);
#endif
			return moduleBuilder;
		}
Beispiel #3
0
        public AssemblyBuilder(bool canSave)
        {
            _canSave = canSave;
            _name = "EnigmaDynamicEmit." + Guid.NewGuid().ToString("N");

            var domain = AppDomain.CurrentDomain;
            _assemblyBuilder = domain.DefineDynamicAssembly(new AssemblyName(_name), canSave ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run);
            _module = canSave
                ? _assemblyBuilder.DefineDynamicModule(_name, _name + ".dll")
                : _assemblyBuilder.DefineDynamicModule(_name);
        }
        public ProjectionAssembly(string name, ProjectionOptions options)
        {
            this.name = name;

            assembly = AppDomain.CurrentDomain.DefineDynamicAssembly
            (
                new AssemblyName(name),
                GetAssemblyAccess(options)
            );

            module = 0 == (options & ProjectionOptions.SaveAssemblies)
                ? assembly.DefineDynamicModule(name)
                : assembly.DefineDynamicModule(name, FileName);
        }
 static NativeDelegateServices()
 {
     var name = new AssemblyName {Name = "NativeDelegateWrapperAssembly"};
     asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
     moduleBuilder = asmBuilder.DefineDynamicModule("NativeDelegateWrapperModule");
     wrapperCache = new Dictionary<KeyValuePair<Type, IntPtr>, Type>();
 }
Beispiel #6
0
        public AssemblyBuilder()
        {
            _name = "EnigmaDynamicEmit." + Guid.NewGuid().ToString("N");

            _assemblyBuilder = System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(_name), AssemblyBuilderAccess.Run);
            _module          = _assemblyBuilder.DefineDynamicModule(_name);
        }
 /// <summary>
 /// Initializes a new instance.
 /// </summary>
 /// <param name="assemblyName">The name of assembly defining proxy types.</param>
 public DynamicProxyBuilder(string assemblyName)
 {
     this.assemblyName = new AssemblyName(assemblyName);
      this.assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(this.assemblyName, AssemblyBuilderAccess.RunAndSave);
      this.moduleBuilder = assemblyBuilder.DefineDynamicModule(this.assemblyName + ".dll");
      this.cache = new Dictionary<Tuple<Type, Type>, Type>();
 }
Beispiel #8
0
 public Assembly(string name, string fileName)
 {
     Name = name;
     FileName = fileName;
     AssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Save);
     ModuleBuilder = AssemblyBuilder.DefineDynamicModule(fileName);
 }
Beispiel #9
0
 static ObjCMethod()
 {
     AssemblyName name = new AssemblyName ();
     name.Name = "MethodProxies";
     builder = AppDomain.CurrentDomain.DefineDynamicAssembly (name, AssemblyBuilderAccess.Run, null, null, null, null, null, true);
     module = builder.DefineDynamicModule ("Proxies");
 }
Beispiel #10
0
 public Emitter(EmitterOptions options)
 {
     _options = options;
     _assemblyName = new AssemblyName(_options.AssemblyName);
     _assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, AssemblyBuilderAccess.RunAndSave);// TODO: temp for debugging .RunAndCollect);
     if (_options.DebugOn)
         _assembly.SetCustomAttribute
         (
             new CustomAttributeBuilder
             (
                 typeof(DebuggableAttribute).GetConstructor
                 (
                     new System.Type[] { typeof(DebuggableAttribute.DebuggingModes) }
                 ),
                 new object[]
                 {
                     DebuggableAttribute.DebuggingModes.DisableOptimizations |
                     DebuggableAttribute.DebuggingModes.Default
                 }
             )
         );
     _module = _assembly.DefineDynamicModule(_assemblyName.Name, _assemblyName.Name + ".dll", _options.DebugOn);
     if (_options.DebugOn)
         _symbolWriter = _module.DefineDocument(_options.SourceFileName, Guid.Empty, Guid.Empty, Guid.Empty);
     _tupleToNative = new Dictionary<Type.TupleType, System.Type>();
 }
Beispiel #11
0
        internal static Type makeRecord(String name,Type basetype)
        {
            if(assembly == null)
            {
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = "RecordAssembly";
            assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,AssemblyBuilderAccess.Run);
            module = assembly.DefineDynamicModule("RecordModule");
            }

            TypeBuilder tb = module.DefineType(name,TypeAttributes.Class|TypeAttributes.Public,basetype);
            Type[] paramTypes = Type.EmptyTypes;
            ConstructorBuilder cb = tb.DefineConstructor(MethodAttributes.Public,
                                                                    CallingConventions.Standard,
                                                                    paramTypes);
            ILGenerator constructorIL = cb.GetILGenerator();
            constructorIL.Emit(OpCodes.Ldarg_0);
            ConstructorInfo superConstructor = basetype.GetConstructor(Type.EmptyTypes);
            constructorIL.Emit(OpCodes.Call, superConstructor);
            constructorIL.Emit(OpCodes.Ret);

            Type t = tb.CreateType();
            //Import.AddType(t); //must do in lisp
            return t;
        }
 public RuntimeDynamicModule()
 {
     _assemblyName = new AssemblyName(DEFAULT_MODULE_NAME);
     _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName,
         AssemblyBuilderAccess.RunAndSave);
     _moduleBuilder = _assemblyBuilder.DefineDynamicModule(DEFAULT_MODULE_NAME, DEFAULT_MODULE_NAME + ".dll");
 }
        public ModuleBuilder ObtainDynamicModule()
        {
            lock (m_lockobj)
            {
                if (m_moduleBuilder == null)
                {
                    AssemblyName assemblyName = new AssemblyName();
                    assemblyName.Name = "DynamicAssemblyProxyGen";

            #if ( DEBUG )
                    m_assemblyBuilder =
                        AppDomain.CurrentDomain.DefineDynamicAssembly(
                        assemblyName,
                        AssemblyBuilderAccess.RunAndSave);
                    m_moduleBuilder = m_assemblyBuilder.DefineDynamicModule(assemblyName.Name, FILE_NAME);
            #else
                    m_assemblyBuilder =
                        AppDomain.CurrentDomain.DefineDynamicAssembly(
                            assemblyName,
                            AssemblyBuilderAccess.Run);
                    m_moduleBuilder = m_assemblyBuilder.DefineDynamicModule(assemblyName.Name, true);
            #endif
                }
            }

            return m_moduleBuilder;
        }
Beispiel #14
0
 public void Reset()
 {
     UniqueCounter++;
     var CurrentAppDomain = AppDomain.CurrentDomain;
     AssemblyBuilder = CurrentAppDomain.DefineDynamicAssembly(new AssemblyName("assembly" + UniqueCounter), AssemblyBuilderAccess.RunAndSave);
     ModuleBuilder = AssemblyBuilder.DefineDynamicModule("module" + UniqueCounter);
 }
Beispiel #15
0
        private static Type getNewObject(DataColumnCollection columns, string className)
        {
            AssemblyName assemblyName = new AssemblyName();

            assemblyName.Name = "YourAssembly";
            System.Reflection.Emit.AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder module      = assemblyBuilder.DefineDynamicModule("YourDynamicModule");
            TypeBuilder   typeBuilder = module.DefineType(className, TypeAttributes.Public);

            foreach (DataColumn column in columns)
            {
                string           propertyName        = column.ColumnName;
                FieldBuilder     field               = typeBuilder.DefineField(propertyName, (column.DataType != typeof(string) && column.AllowDBNull) ? typeof(Nullable <>).MakeGenericType(column.DataType):column.DataType, FieldAttributes.Public);
                PropertyBuilder  property            = typeBuilder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.None, column.DataType, new Type[] { (column.AllowDBNull && column.DataType != typeof(string))? typeof(Nullable <>).MakeGenericType(column.DataType) : column.DataType });
                MethodAttributes GetSetAttr          = MethodAttributes.Public | MethodAttributes.HideBySig;
                MethodBuilder    currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, column.DataType, new Type[] { (column.AllowDBNull && column.DataType != typeof(string)) ? typeof(Nullable <>).MakeGenericType(column.DataType) : column.DataType }); // Type.EmptyTypes);
                ILGenerator      currGetIL           = currGetPropMthdBldr.GetILGenerator();
                currGetIL.Emit(OpCodes.Ldarg_0);
                currGetIL.Emit(OpCodes.Ldfld, field);
                currGetIL.Emit(OpCodes.Ret);
                MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { (column.AllowDBNull && column.DataType != typeof(string)) ? typeof(Nullable <>).MakeGenericType(column.DataType) : column.DataType });
                ILGenerator   currSetIL           = currSetPropMthdBldr.GetILGenerator();
                currSetIL.Emit(OpCodes.Ldarg_0);
                currSetIL.Emit(OpCodes.Ldarg_1);
                currSetIL.Emit(OpCodes.Stfld, field);
                currSetIL.Emit(OpCodes.Ret);
                property.SetGetMethod(currGetPropMthdBldr);
                property.SetSetMethod(currSetPropMthdBldr);
            }
            Type obj = typeBuilder.CreateType();

            return(obj);
        }
Beispiel #16
0
        public DynamicAssembly()
        {
            int assemblyNumber = Interlocked.Increment(ref _assemblyCount);
            _assemblyName = new AssemblyName {
                Name = String.Format("Quokka.DynamicAssembly.N{0}", assemblyNumber)
            };
            string moduleName = AssemblyName.Name;
            _dynamicClassNamespace = AssemblyName.Name;

            if (CreateFiles)
            {
                _assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(
                    AssemblyName, AssemblyBuilderAccess.RunAndSave);

                // Add a debuggable attribute to the assembly saying to disable optimizations
                // See http://blogs.msdn.com/rmbyers/archive/2005/06/26/432922.aspx
                Type daType = typeof (DebuggableAttribute);
                ConstructorInfo daCtor = daType.GetConstructor(new[] {typeof (bool), typeof (bool)});
                var daBuilder = new CustomAttributeBuilder(daCtor, new object[] {true, true});
                _assemblyBuilder.SetCustomAttribute(daBuilder);

                _moduleBuilder = _assemblyBuilder.DefineDynamicModule(moduleName);
                _canSave = true;
            }
            else
            {
                _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(AssemblyName, AssemblyBuilderAccess.Run);
                _moduleBuilder = _assemblyBuilder.DefineDynamicModule(moduleName);
            }
        }
 public void FixtureSetUp()
 {
     //assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("TestAssembly"), AssemblyBuilderAccess.RunAndSave);
     //moduleBuilder = assemblyBuilder.DefineDynamicModule("TestAssembly", "TestAssembly.dll");
     assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("TestAssembly"), AssemblyBuilderAccess.Run);
     moduleBuilder = assemblyBuilder.DefineDynamicModule("TestAssembly");
 }
Beispiel #18
0
 /// <summary>
 /// A static constructor.
 /// </summary>
 static WrapFactory()
 {
     AssemblyName asmName = new AssemblyName();
     asmName.Name = "SqlWrapperDynamicAsm";
     m_asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
     m_modBuilder = m_asmBuilder.DefineDynamicModule("SqlWrapperDynamicModule");
 }
Beispiel #19
0
        static NativeCall() {

            // The static constructor is responsible for generating the
            // assembly and the methods that implement the IJW thunks.
            //
            // To do this, we actually use reflection on the INativeCall
            // interface (defined below) and generate the required thunk 
            // code based on the method signatures.

            AssemblyName aname = new AssemblyName();
            aname.Name = "e__NativeCall_Assembly";
            AssemblyBuilderAccess aa = AssemblyBuilderAccess.Run;

            aBuilder = Thread.GetDomain().DefineDynamicAssembly(aname, aa);
            mBuilder = aBuilder.DefineDynamicModule("e__NativeCall_Module");

            TypeAttributes ta = TypeAttributes.Public;
            TypeBuilder tBuilder = mBuilder.DefineType("e__NativeCall", ta);

            Type iType = typeof(INativeCall);
            tBuilder.AddInterfaceImplementation(iType);

            // Use reflection to loop over the INativeCall interface methods, 
            // calling GenerateThunk to create a managed thunk for each one.

            foreach (MethodInfo method in iType.GetMethods()) {
                GenerateThunk(tBuilder, method);
            }
            
            Type theType = tBuilder.CreateType();

            Impl = (INativeCall)Activator.CreateInstance(theType);

        }
Beispiel #20
0
        public MethodInfo GetInvokeMethod(string methodName, Type returnType, Type[] types)
        {
            string entryName = methodName;
            if (assemblyBuilder == null)
            {
                AssemblyName assemblyName = new AssemblyName(AssemblyName);
                assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                moduleBuilder = assemblyBuilder.DefineDynamicModule(AssemblyName);
            }

            var defineType = moduleBuilder.DefineType(GetDefineTypeName(methodName));
            var methodBuilder = defineType.DefinePInvokeMethod(methodName, dllName, entryName,
                       MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.PinvokeImpl,
                       CallingConventions.Standard,
                       returnType, types,
                       CallingConvention, CharSet);
            if ((returnType != null) && (returnType != typeof(void)))
            {
                methodBuilder.SetImplementationFlags(MethodImplAttributes.PreserveSig | methodBuilder.GetMethodImplementationFlags());
            }
            var type = defineType.CreateType();

            var method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.Static);
            return method;
        }
         /// <summary>
        /// Initializes a new instance of the <see cref="SetAccessorFactory"/> class.
        /// </summary>
        /// <param name="allowCodeGeneration">if set to <c>true</c> [allow code generation].</param>
        public SetAccessorFactory(bool allowCodeGeneration)
		{
            if (allowCodeGeneration)
            {
                // Detect runtime environment and create the appropriate factory
                if (Environment.Version.Major >= 2)
                {
                    _createPropertySetAccessor = new CreatePropertySetAccessor(CreateDynamicPropertySetAccessor);
                    _createFieldSetAccessor = new CreateFieldSetAccessor(CreateDynamicFieldSetAccessor);
                }
                else
                {
                    AssemblyName assemblyName = new AssemblyName();
                    assemblyName.Name = "iBATIS.FastSetAccessor" + HashCodeProvider.GetIdentityHashCode(this);

                    // Create a new assembly with one module
                    _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
                    _moduleBuilder = _assemblyBuilder.DefineDynamicModule(assemblyName.Name + ".dll");

                    _createPropertySetAccessor = new CreatePropertySetAccessor(CreatePropertyAccessor);
                    _createFieldSetAccessor = new CreateFieldSetAccessor(CreateFieldAccessor);
                }
            }
            else
            {
                _createPropertySetAccessor = new CreatePropertySetAccessor(CreateReflectionPropertySetAccessor);
                _createFieldSetAccessor = new CreateFieldSetAccessor(CreateReflectionFieldSetAccessor);
            }
        }
Beispiel #22
0
 public ILDynamicTypeImpl(string name, Type baseType, Type[] interfaces)
 {
     _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.RunAndCollect);
     _moduleBuilder = _assemblyBuilder.DefineDynamicModule(name + ".dll", true);
     _typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, baseType, interfaces);
     _forbidenInstructions = new ILGenForbidenInstructionsCheating(_typeBuilder);
 }
Beispiel #23
0
 public GenContext(string assyName, string directory, CompilerMode mode)
 {
     AssemblyName aname = new AssemblyName(assyName);
     _assyBldr = AppDomain.CurrentDomain.DefineDynamicAssembly(aname, AssemblyBuilderAccess.RunAndSave,directory);
     _moduleBldr = _assyBldr.DefineDynamicModule(aname.Name, aname.Name + ".dll", true);
     _mode = mode;
 }
Beispiel #24
0
 /// <summary>
 /// 
 /// </summary>
 public RestAPIManager()
 {
     AssemblyName aName = new AssemblyName("AutoGenerated");
     assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);
     ModuleBuilder mb = assemblyBuilder.DefineDynamicModule("Rest", "AutoGenerated.dll");
     typeBuilder = mb.DefineType("RestAPI", TypeAttributes.Public);
 }
Beispiel #25
0
 private void CreateAssembly()
 {  //to create an assembly programmatically
     AssemblyName Name = new AssemblyName("NaiveORM0Classes");
     AppDomain Domain = Thread.GetDomain();
     _Builder = Domain.DefineDynamicAssembly(Name, AssemblyBuilderAccess.Run);
     _Module = _Builder.DefineDynamicModule("NaiveORM0ClassesM");
 }
Beispiel #26
0
        // Главная функция кодогенератора. Получает на вход синтаксическое дерево, обходит его и в хое его обхода с
        //     помощью библиотеки System.Reflection строит исполняемый файл на MSIL, который потом можно запускать вне компилятора (однако, на компьютере должна быть установлена .Net Framwork)
        //     Путь к файлу задаётся в интерфейсе компилятора
        public bool Proceed(Node Tree, RichTextBox RTB, string FileName)
        {
            _Tree = Tree;
            _RTB  = RTB;
            InitFileName(FileName);

            try
            {
                Reflect.AssemblyName Name = new Reflect.AssemblyName(FileName);
                AsmBuilder       = System.AppDomain.CurrentDomain.DefineDynamicAssembly(Name, Emit.AssemblyBuilderAccess.Save);
                ModBuilder       = AsmBuilder.DefineDynamicModule(FileName);
                TypeTable        = new Collections.Dictionary <string, Emit.TypeBuilder>();
                CreatedTypeTable = new Collections.Dictionary <string, System.Type>();
                SymbolTable      = new Collections.List <Collections.Dictionary <string, Emit.LocalBuilder> >();

                BeforeCompile(Tree);
                CreateCode(Tree);

                AsmBuilder.Save(FileName);
                this.SymbolTable        = null;
                this.AssemblerGenerator = null;
                this.TypeTable          = null;

                File.Move(FileName, FileName + ".exe");
                File.Delete(FileName);

                return(true);
            }
            catch (System.Exception Exc)
            {
                _RTB.Text = Exc.Message;

                return(false);
            }
        }
        static DynamicAssemblyManager()
        {
#if !SILVERLIGHT
            assemblyName = new AssemblyName("NLiteDynamicAssembly");
            assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                assemblyName,
                AssemblyBuilderAccess.RunAndSave
                );

            moduleBuilder = assemblyBuilder.DefineDynamicModule(
                assemblyName.Name,
                assemblyName.Name + ".dll",
                true);

            Module = assemblyBuilder.GetModules().FirstOrDefault();
           
#else
            assemblyName = new AssemblyName("EmitMapperAssembly.SL");
            assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                  assemblyName,
                  AssemblyBuilderAccess.Run
                  );
            moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, true);
#endif
        }
Beispiel #28
0
		public void CreateDynamicMethod()
		{
#if SAVE_ASSEMBLY
			if (_assemblyBuilder == null)
			{
				AssemblyName assemblyName = new AssemblyName("ExpressionAssembly");
				_assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave, "I:\\Trash");
				_moduleBuilder = _assemblyBuilder.DefineDynamicModule("ExpressionModule", "ExpressionModule.module");
			}

			string typeName = String.Format("Expression{0}", _typeCount);
			_typeCount++;

			_typeBuilder = _moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public);
			
			FieldBuilder filedBuilder = _typeBuilder.DefineField("Source", typeof(string), FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal);
			filedBuilder.SetConstant(_source);

			_methodBuilder = _typeBuilder.DefineMethod("Evaluate", MethodAttributes.Public | MethodAttributes.Static, typeof(object), new Type[] { typeof(object[]) });
			_ilGenerator = _methodBuilder.GetILGenerator();
#else
			_dynamicMethod = new DynamicMethod("Expression", typeof(object), new Type[] { typeof(object[]) }, GetType().Module);
			_ilGenerator = _dynamicMethod.GetILGenerator();
#endif
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public DynamicAssembly(string name)
 {
     _assemblyName = new AssemblyName(name);
     _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName,
         AssemblyBuilderAccess.RunAndSave, Directory.GetCurrentDirectory());
     _moduleBuilder = _assemblyBuilder.DefineDynamicModule(_assemblyName.Name, _assemblyName.Name + ".dll");
 }
        public DynamicEntityEmitter(bool save)
        {
            this.saveFile = save;
            this.theFileName = this.assemblyName + ".dll";

            AssemblyBuilderAccess assemblyBuilderAccess = this.saveFile ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run;
            this.dynamicAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(this.assemblyName), assemblyBuilderAccess);
            if (this.saveFile)
            {
                this.moduleBuilder = dynamicAssembly.DefineDynamicModule("MainModule", this.theFileName);
            }
            else
            {
                this.moduleBuilder = dynamicAssembly.DefineDynamicModule("MainModule");
            }
        } 
Beispiel #31
0
    public CodeGen(Stmt stmt, string moduleName)
    {
        if (IO.Path.GetFileName(moduleName) != moduleName)
        {
            throw new System.Exception("can only output into current directory!");
        }

        Reflect.AssemblyName name        = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(moduleName));
        Emit.AssemblyBuilder asmb        = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save);
        Emit.ModuleBuilder   modb        = asmb.DefineDynamicModule(moduleName);
        Emit.TypeBuilder     typeBuilder = modb.DefineType("Foo");

        Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);

        // CodeGenerator
        this.il          = methb.GetILGenerator();
        this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>();

        // Go Compile!
        this.GenStmt(stmt);

        il.Emit(Emit.OpCodes.Ret);
        typeBuilder.CreateType();
        modb.CreateGlobalFunctions();
        asmb.SetEntryPoint(methb);
        asmb.Save(moduleName);
        this.symbolTable = null;
        this.il          = null;
    }
 public ILDynamicMethodDebugImpl(string name, Type delegateType, Type thisType)
 {
     _delegateType = delegateType;
     _expectedLength = 64;
     var mi = delegateType.GetMethod("Invoke");
     var uniqueName = ILDynamicTypeDebugImpl.UniqueName(name);
     _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(uniqueName), AssemblyBuilderAccess.RunAndSave, DynamicILDirectoryPath.DynamicIL);
     _moduleBuilder = _assemblyBuilder.DefineDynamicModule(uniqueName + ".dll", true);
     var sourceCodeFileName = Path.Combine(DynamicILDirectoryPath.DynamicIL, uniqueName + ".il");
     _symbolDocumentWriter = _moduleBuilder.DefineDocument(sourceCodeFileName, SymDocumentType.Text, SymLanguageType.ILAssembly, SymLanguageVendor.Microsoft);
     _sourceCodeWriter = new SourceCodeWriter(sourceCodeFileName, _symbolDocumentWriter);
     Type[] parameterTypes;
     if (thisType != null)
     {
         parameterTypes = new[] { thisType }.Concat(mi.GetParameters().Select(pi => pi.ParameterType)).ToArray();
     }
     else
     {
         parameterTypes = mi.GetParameters().Select(pi => pi.ParameterType).ToArray();
     }
     _sourceCodeWriter.StartMethod(name, mi.ReturnType, parameterTypes, MethodAttributes.Static);
     _typeBuilder = _moduleBuilder.DefineType(name, TypeAttributes.Public, typeof(object), Type.EmptyTypes);
     _forbidenInstructions = new ILGenForbidenInstructionsCheating(_typeBuilder);
     _dynamicMethod = _typeBuilder.DefineMethod("Invoke", MethodAttributes.Public | MethodAttributes.Static, mi.ReturnType, parameterTypes);
     for (int i = 0; i < parameterTypes.Length; i++)
     {
         _dynamicMethod.DefineParameter(i + 1, ParameterAttributes.In, string.Format("arg{0}", i));
     }
 }
Beispiel #33
0
 static PropertyAccessor()
 {
     AssemblyName asmName = new AssemblyName();
     asmName.Name = "$Assembly.Hprose.IO.PropertyAccessor";
     asmBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.Run);
     modBuilder = asmBuilder.DefineDynamicModule("$Module.PropertyAccessor");
 }
Beispiel #34
0
        public CodeGenerator(Expression pExpression, String pModuleName, ref LogHandler rLogHandler)
        {
            _symbolTable  = new Dictionary <String, Emit.LocalBuilder>();
            _assemblyName = new Reflect.AssemblyName(Path.GetFileNameWithoutExtension(pModuleName));

            _statement = pExpression;

            //Init Assembly
            _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemblyName, Emit.AssemblyBuilderAccess.Save);
            _moduleBuilder   = _assemblyBuilder.DefineDynamicModule(pModuleName);
            _typeBuilder     = _moduleBuilder.DefineType("PascalCompilerType");
            _methodBuilder   = _typeBuilder.DefineMethod
                               (
                "Main",
                Reflect.MethodAttributes.Static,
                typeof(void),
                Type.EmptyTypes
                               );
            _ilGenerator = _methodBuilder.GetILGenerator();

            //Actual Work
            GenerateStatement(_statement, null);
            _ilGenerator.Emit(Emit.OpCodes.Ret);

            //Finalizing Work
            _typeBuilder.CreateType();
            _moduleBuilder.CreateGlobalFunctions();
            _assemblyBuilder.SetEntryPoint(_methodBuilder);
            _assemblyBuilder.Save(pModuleName);
        }
        /// <summary>
        /// Initializes the runtime compiler and metadata references for dynamic assembly.
        /// </summary>
        public RunTimeCreator()
        {
            usedNameDict = new Dictionary<string, int>();
            // Set references to runtime compiling
            isCompiled = new List<string>();
            var t = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            metadataRef = new List<MetadataReference>();
            metadataRef.Add(MetadataFileReference.CreateAssemblyReference("mscorlib"));
            metadataRef.Add(new MetadataFileReference(typeof(Strategy.MyMogre).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(Strategy.Game).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(GameObjectControl.Game_Objects.StaticGameObjectBox.StaticGameObject).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(Team).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(System.Linq.Enumerable).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(LinkedList<>).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(Path.GetFullPath((new Uri(t + "\\\\Mogre.dll")).LocalPath)));
            metadataRef.Add(new MetadataFileReference(typeof(PropertyManager).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(GameObjectControl.Game_Objects.StaticGameObjectBox.IStaticGameObject).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(ActionAnswer).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(PropertyEnum).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(XmlLoadException).Assembly.Location));
            metadataRef.Add(new MetadataFileReference(typeof(ConstructorFieldAttribute).Assembly.Location));

            comilationOption = new CompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            assemblyBuilder =
                AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("DynamicAssembly" + Guid.NewGuid()),
                                                              AssemblyBuilderAccess.RunAndCollect);
            moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicModule");
        }
        internal ReflectionEmitModuleInfo(ScriptEngine engine)
        {
            Engine = engine;

            // Create a dynamic assembly and module.
            AssemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(
                new AssemblyName("Nitro Dynamic Assembly"), AssemblyBuilderAccess.Run);

            // Create a dynamic module.
            ModuleBuilder = AssemblyBuilder.DefineDynamicModule("Module", ScriptEngine.EnableDebugging);
        }
 public ILCodeGen(string name)
 {
     this.symtab        = Symboltable.Instance;
     this.program_name  = name;
     this.asname        = new Reflect.AssemblyName(name);
     this.asmb          = System.AppDomain.CurrentDomain.DefineDynamicAssembly(asname, Emit.AssemblyBuilderAccess.Save);
     this.modb          = asmb.DefineDynamicModule(name);
     this.typeBuilder   = modb.DefineType("fpc2IL");
     this.mbuilderTable = new Hashtable();
     this.fbuilderTable = new Hashtable();
     this.lbuilderTable = new Hashtable();
 }
Beispiel #38
0
        private void inicializar(string nombreCodigoFuente, string nombrePrograma)
        {
            if (TablaDireccionesSimbolos.Count > 0)
            {
                throw new System.Exception("ERROR-0002: Tabla de direcciones de variables ha sido inicializada previamente");
            }

            String rutaEjecutable = IO.Path.GetDirectoryName(nombrePrograma);

            //Describo el identificador unico del ensamblado que se esta generando
            nombre = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(nombrePrograma));

            //Creo la representacion basica del ensamblado creado de forma dinamica (assembly)
            if (rutaEjecutable.Length > 0)
            {
                asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(nombre, Emit.AssemblyBuilderAccess.RunAndSave, rutaEjecutable);
            }
            else
            {
                asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(nombre, Emit.AssemblyBuilderAccess.RunAndSave);
            }



            Console.WriteLine("Common Runtime usado para generar el ejecutable del programa: " + asmb.ImageRuntimeVersion);
            Console.WriteLine("Se esta ejecutando el compilador bajo el CLR version {0}", Environment.Version);

            //Defino un nuevo modulo de .net de forma dinamica
            modb = asmb.DefineDynamicModule(IO.Path.GetFileName(nombrePrograma), false);

            //Creo una nueva clase en el Il Generator stream
            typeBuilder = modb.DefineType("pseudoGenerado");

            //Debido a que los programas en este tiny solo cuentan con un unico metodo principal (Main) de forma estructurada
            //como un truco defino el metodo Main en un objeto por defecto para ejecutar todas las acciones
            //expresadas por el lenguaje alli.
            //formato: NOMBRE -> Main   TIPO-> Static  RETORNA-> void  PARAMETROS-> vacios
            methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.HideBySig | Reflect.MethodAttributes.Static | Reflect.MethodAttributes.Public, typeof(void), System.Type.EmptyTypes);

            //Inicializo/Creo el generador/stream de codigo IL con el metodo donde generare el codigo actualmente
            this.il = methb.GetILGenerator();

            //Para iniciar el programa Emito una primera instruccion vacia (no hace nada)
            il.Emit(Emit.OpCodes.Nop);
        }
        private static TypeBuilder GetTypeBuilder(string assemblyName, string typeName)
        {
            var typeSignature = typeName;
            var an            = new AssemblyName(assemblyName);

            System.Reflection.Emit.AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("GeneratedModule");
            TypeBuilder   tb            = moduleBuilder.DefineType(typeSignature,
                                                                   TypeAttributes.Public |
                                                                   TypeAttributes.Class |
                                                                   TypeAttributes.AutoClass |
                                                                   TypeAttributes.AnsiClass |
                                                                   TypeAttributes.BeforeFieldInit |
                                                                   TypeAttributes.AutoLayout,
                                                                   null);

            return(tb);
        }
        /// <summary>
        /// Build a new provider
        /// </summary>
        /// <param name="assemblyName">Name of the assembly to build.</param>
        public SigilFunctionProvider(string assemblyName = null)
        {
            AlreadyBuildedMethods = new Dictionary <Type, IResponse>();

            if (string.IsNullOrEmpty(assemblyName))
            {
                return;
            }

            this.assemblyName = new AssemblyName(assemblyName);
#if RUN_ONLY
            var attributes = System.Reflection.Emit.AssemblyBuilderAccess.Run;
#else
            var attributes = System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave;
#endif
            assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(this.assemblyName, attributes, Path.GetTempPath());
            moduleBuilder   = assemblyBuilder.DefineDynamicModule($"{assemblyName}.dll");
            typeBuilder     = moduleBuilder.DefineType($"{this.assemblyName.Name}.Handler", TypeAttributes.Public);
        }
        static void InitializeRuntimeAssemblyBuilder()
        {
            if (runtimeEmittedAssembly == null)
            {
                AssemblyName assemblyName = new AssemblyName(RUNTIME_ASSEMBLY_NAME);

                assemblyName.CultureInfo           = System.Globalization.CultureInfo.InvariantCulture;
                assemblyName.Flags                 = AssemblyNameFlags.None;
                assemblyName.ProcessorArchitecture = ProcessorArchitecture.MSIL;
                assemblyName.VersionCompatibility  = System.Configuration.Assemblies.AssemblyVersionCompatibility.SameDomain;

                runtimeEmittedAssembly = System.AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            }

            if (runtimeEmittedModule == null)
            {
                runtimeEmittedModule = runtimeEmittedAssembly.DefineDynamicModule(RUNTIME_ASSEMBLY_NAME, true);
            }
        }
Beispiel #42
0
        private static TypeBuilder GetTypeBuilder(AttributeFormat format, Type parentClass)
        {
            string       typeSignature = format.type;
            AssemblyName assemblyName  = new AssemblyName(typeSignature);

            System.Reflection.Emit.AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
            TypeBuilder   typeBuilder   = moduleBuilder.DefineType(
                typeSignature,
                TypeAttributes.Public |
                TypeAttributes.Class |
                TypeAttributes.AutoClass |
                TypeAttributes.AnsiClass |
                TypeAttributes.BeforeFieldInit |
                TypeAttributes.AutoLayout,
                parentClass);

            return(typeBuilder);
        }
Beispiel #43
0
        public AssemblyGen(TypeDeclaration methodDec, string moduleName, string dllProbeDirectory)
        {
            if (IO.Path.GetFileName(moduleName) != moduleName)
            {
                throw new System.Exception("can only output into current directory!");
            }

            this.dllProbeDirectory = dllProbeDirectory;

            typeList = new List <TypeGen>();

            Reflect.AssemblyName name = new Reflect.AssemblyName(IO.Path.GetFileNameWithoutExtension(moduleName));
            Emit.AssemblyBuilder asmb = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save);
            Emit.ModuleBuilder   modb = asmb.DefineDynamicModule(moduleName);
            GenerateType(methodDec, modb, dllProbeDirectory);
            modb.CreateGlobalFunctions();
            asmb.SetEntryPoint(GetEntryPoint());
            asmb.Save(moduleName);
        }
Beispiel #44
0
    public static Type BuildPropertyObject(System.Collections.Generic.IEnumerable <System.Collections.Generic.KeyValuePair <string, Type> > obj)
    {
        string nameOfDLL      = "magic.dll";
        string nameOfAssembly = "magic_Assembly";
        string nameOfModule   = "magic_Module";
        string nameOfType     = "magic_Type";

        System.Reflection.AssemblyName assemblyName = new System.Reflection.AssemblyName {
            Name = nameOfAssembly
        };
        System.Reflection.Emit.AssemblyBuilder assemblyBuilder = System.Threading.Thread.GetDomain().DefineDynamicAssembly(assemblyName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave);
        System.Reflection.Emit.ModuleBuilder   moduleBuilder   = assemblyBuilder.DefineDynamicModule(nameOfModule, nameOfDLL);
        System.Reflection.Emit.TypeBuilder     typeBuilder     = moduleBuilder.DefineType(nameOfType, System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Class);
        foreach (var prop in obj)
        {
            string Name     = prop.Key;
            Type   DataType = prop.Value;
            System.Reflection.Emit.FieldBuilder    field               = typeBuilder.DefineField("_" + Name, DataType, System.Reflection.FieldAttributes.Private);
            System.Reflection.Emit.PropertyBuilder propertyBuilder     = typeBuilder.DefineProperty(Name, System.Reflection.PropertyAttributes.SpecialName, DataType, null);
            System.Reflection.MethodAttributes     methodAttributes    = System.Reflection.MethodAttributes.Public | System.Reflection.MethodAttributes.HideBySig | System.Reflection.MethodAttributes.SpecialName;
            System.Reflection.Emit.MethodBuilder   methodBuilderGetter = typeBuilder.DefineMethod("get_" + Name, methodAttributes, DataType, new Type[] { });
            System.Reflection.Emit.MethodBuilder   methodBuilderSetter = typeBuilder.DefineMethod("set_" + Name, methodAttributes, typeof(void), new Type[] { DataType });
            System.Reflection.Emit.ILGenerator     ilGeneratorGetter   = methodBuilderGetter.GetILGenerator();
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ldfld, field);
            ilGeneratorGetter.Emit(System.Reflection.Emit.OpCodes.Ret);
            System.Reflection.Emit.ILGenerator ilGeneratorSetter = methodBuilderSetter.GetILGenerator();
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_0);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ldarg_1);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Stfld, field);
            ilGeneratorSetter.Emit(System.Reflection.Emit.OpCodes.Ret);
            propertyBuilder.SetGetMethod(methodBuilderGetter);
            propertyBuilder.SetSetMethod(methodBuilderSetter);
        }
        // Yes! you must do this, it should not be needed but it is!
        Type dynamicType = typeBuilder.CreateType();

        // Save to file
        assemblyBuilder.Save(nameOfDLL);
        return(dynamicType);
    }
Beispiel #45
0
    public CodeGen(stmt stmt, string moduleName, int count)
    {
        if (IO.Path.GetFileName(moduleName) != moduleName)
        {
            throw new System.Exception("can only output into current directory!");
        }
        stmts = stmt;

        Reflect.AssemblyName name        = new Reflect.AssemblyName("FAJF"); //name of the assembly
        Emit.AssemblyBuilder asmb        = System.AppDomain.CurrentDomain.DefineDynamicAssembly(name, Emit.AssemblyBuilderAccess.Save);
        Emit.ModuleBuilder   modb        = asmb.DefineDynamicModule(moduleName);
        Emit.TypeBuilder     typeBuilder = modb.DefineType("resister"); //name of the class

        Emit.MethodBuilder methb = typeBuilder.DefineMethod("Main", Reflect.MethodAttributes.Static, typeof(void), System.Type.EmptyTypes);

        // CodeGenerator
        this.il          = methb.GetILGenerator();
        this.symbolTable = new Collections.Dictionary <string, Emit.LocalBuilder>();
        counting         = 0;
        counter          = count;
        counters         = 0;



        // Go Compile!
        this.GenStmt(stmt);

        il.Emit(Emit.OpCodes.Ret);
        typeBuilder.CreateType();
        modb.CreateGlobalFunctions();
        asmb.SetEntryPoint(methb);
        asmb.Save(moduleName);
        // this.il.EmitWriteLine("press any key to continue");

        this.symbolTable = null;
        this.il          = null;
        System.Diagnostics.Process.Start(moduleName);
    }
Beispiel #46
0
        private static Type getNewObject(DataColumnCollection columns, string className)
        {
            AssemblyName assemblyName = new AssemblyName();

            assemblyName.Name = WebConfigurationManager.AppSettings["AppName"].ToString();
            System.Reflection.Emit.AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
            ModuleBuilder module      = assemblyBuilder.DefineDynamicModule("YourDynamicModule");
            TypeBuilder   typeBuilder = module.DefineType(className, TypeAttributes.Public);

            foreach (DataColumn column in columns)
            {
                string propertyName = column.ColumnName;
                //if (column.ColumnName == "NightPrice")
                //{
                //    column.DataType = typeof(float);
                //}

                FieldBuilder     field               = typeBuilder.DefineField(propertyName, column.DataType, FieldAttributes.Public);
                PropertyBuilder  property            = typeBuilder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.None, column.DataType, new Type[] { column.DataType });
                MethodAttributes GetSetAttr          = MethodAttributes.Public | MethodAttributes.HideBySig;
                MethodBuilder    currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, column.DataType, new Type[] { column.DataType }); // Type.EmptyTypes);
                ILGenerator      currGetIL           = currGetPropMthdBldr.GetILGenerator();
                currGetIL.Emit(OpCodes.Ldarg_0);
                currGetIL.Emit(OpCodes.Ldfld, field);
                currGetIL.Emit(OpCodes.Ret);
                MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { column.DataType });
                ILGenerator   currSetIL           = currSetPropMthdBldr.GetILGenerator();
                currSetIL.Emit(OpCodes.Ldarg_0);
                currSetIL.Emit(OpCodes.Ldarg_1);
                currSetIL.Emit(OpCodes.Stfld, field);
                currSetIL.Emit(OpCodes.Ret);
                property.SetGetMethod(currGetPropMthdBldr);
                property.SetSetMethod(currSetPropMthdBldr);
            }
            Type obj = typeBuilder.CreateType();

            return(obj);
        }
Beispiel #47
0
        /// <summary>
        /// 将一个类型动态生成另一个子类,并在其继承的接口上打上[ServiceContract]标记
        /// </summary>
        /// <param name="sourceType"></param>
        /// <returns></returns>
        public static Type Wrapper(Type sourceType)
        {
            AppDomain    myCurrentDomain = AppDomain.CurrentDomain;
            AssemblyName myAssemblyName;//= new AssemblyName();

            myAssemblyName = sourceType.Assembly.GetName();

            System.Reflection.Emit.AssemblyBuilder myAssemblyBuilder = myCurrentDomain.DefineDynamicAssembly
                                                                           (myAssemblyName, AssemblyBuilderAccess.Run);

            ModuleBuilder myModuleBuilder = myAssemblyBuilder.
                                            DefineDynamicModule("TempModule");

            Type[] interfaces    = sourceType.GetInterfaces();
            Type[] ExtInterfaces = new Type[interfaces.Count()];
            int    index         = 0;

            foreach (Type aInterface in interfaces)
            {
                TypeBuilder ExtInterfaceTypeBuilder = myModuleBuilder.DefineType
                                                          (aInterface.Name + suffix, TypeAttributes.Public |
                                                          TypeAttributes.Interface | TypeAttributes.Abstract);
                var methods = aInterface.GetMethods();
                foreach (var method in methods)
                {
                    var    aparams = method.GetParameters();
                    Type[] param   = new Type[aparams.Count()];
                    for (int i = 0; i < aparams.Count(); i++)
                    {
                        param[i] = aparams[i].ParameterType;
                    }

                    var methodBuilder = ExtInterfaceTypeBuilder.DefineMethod(method.Name, method.Attributes,
                                                                             CallingConventions.Standard, method.ReturnType, param);
                    for (int i = 0; i < aparams.Count(); i++)
                    {
                        if (aparams[i].IsOut)///TODO:其他参数属性处理,目前仅处理(Out),其他视为None
                        {
                            methodBuilder.DefineParameter(1, ParameterAttributes.Out, aparams[i].Name);
                        }
                        else
                        {
                            methodBuilder.DefineParameter(1, ParameterAttributes.None, aparams[i].Name);
                        }
                    }

                    ConstructorInfo        cinfo     = typeof(OperationContractAttribute).GetConstructors()[0];
                    CustomAttributeBuilder caBuilder = new CustomAttributeBuilder(cinfo, new object[] { });
                    methodBuilder.SetCustomAttribute(caBuilder);
                }
                var acinfo     = typeof(ServiceContractAttribute).GetConstructors()[0];
                var acaBuilder = new CustomAttributeBuilder(acinfo, new object[] { });
                ExtInterfaces[index++] = ExtInterfaceTypeBuilder.CreateType();
                ExtInterfaceTypeBuilder.SetCustomAttribute(acaBuilder);
            }
            TypeBuilder ExtClassTypeBuilder = myModuleBuilder.DefineType
                                                  (sourceType.Name + suffix, TypeAttributes.Public, sourceType, ExtInterfaces);

            Type rType = ExtClassTypeBuilder.CreateType();

            return(rType);
        }
Beispiel #48
0
        private AssemblyBuilder CreateExecutable(string name)
        {
            ILGenerator il;

            name = name.Replace('\\', '/');
            string exename  = name.Contains('/') ? name.Substring(name.LastIndexOf('/') + 1) : name;
            string pathname = name.Contains('/') ? name.Remove(name.LastIndexOf('/')) : null;
            string asmname  = exename.Contains('.') ? exename.Remove(exename.LastIndexOf('.')) : exename;
            //
            // We are generating a dynamic assembly here.
            //
            // Get type information from the runtime assembly
            var  asm_runtime = Assembly.Load("GameCreator.Runtime");
            var  asm_gamei   = Assembly.Load("GameCreator.Runtime.Game.Interpreted");
            var  asm_game    = Assembly.Load("GameCreator.Runtime.Game");
            Type t_gamei     = asm_gamei.GetType("GameCreator.Runtime.Game.Interpreted.InterpretedGame");
            Type t_game      = asm_game.GetType("GameCreator.Runtime.Game.Game");
            Type t_ext       = typeof(ResourceExtensions);
            Type t_obj       = typeof(Framework.Object);
            Type t_room      = typeof(Room);
            Type t_event     = typeof(Event);
            Type t_lib       = typeof(Framework.ActionLibrary);
            Type t_context   = typeof(LibraryContext);
            Type t_rcontext  = typeof(ResourceContext);

            // Define our dynamic assembly
            System.Reflection.Emit.AssemblyBuilder asm = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(asmname), AssemblyBuilderAccess.RunAndSave, pathname);
            ModuleBuilder mod = asm.DefineDynamicModule(exename, exename);
            // Define our Program type
            TypeBuilder program = mod.DefineType(string.Format("{0}.Program", asmname));

            System.Resources.IResourceWriter resw = mod.DefineResource(string.Format("{0}.Program.resources", asmname), string.Empty);
            FieldBuilder  resourceManager         = program.DefineField("resourceManager", typeof(System.Resources.ResourceManager), FieldAttributes.Static);
            MethodBuilder GetResourceManager      = program.DefineMethod("GetResourceManager", MethodAttributes.Static, typeof(System.Resources.ResourceManager), Type.EmptyTypes);

            il = GetResourceManager.GetILGenerator();
            System.Reflection.Emit.Label grm_l_1 = il.DefineLabel();
            il.Emit(OpCodes.Ldsfld, resourceManager);
            il.Emit(OpCodes.Dup);
            il.Emit(OpCodes.Brtrue_S, grm_l_1);
            il.Emit(OpCodes.Pop);
            il.Emit(OpCodes.Ldstr, string.Format("{0}.Program", asmname));
            il.Emit(OpCodes.Ldtoken, program);
            il.Emit(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public));
            il.Emit(OpCodes.Callvirt, typeof(Type).GetProperty("Assembly").GetGetMethod());
            il.Emit(OpCodes.Newobj, typeof(System.Resources.ResourceManager).GetConstructor(new Type[] { typeof(string), typeof(Assembly) }));
            il.Emit(OpCodes.Dup);
            il.Emit(OpCodes.Stsfld, resourceManager);
            il.MarkLabel(grm_l_1);
            il.Emit(OpCodes.Ret);
            //program.SetCustomAttribute(new CustomAttributeBuilder(typeof(STAThreadAttribute).GetConstructor(new Type[] { }), new object[] { }));
            // our static Main() function
            // {
            //   GameCreator.Runtime.Object obj;
            //   GameCreator.Runtime.Event ev;
            //   GameCreator.Runtime.ActionLibrary lib;
            //   GameCreator.Runtime.Game.Init();
            //   ...
            //   lib = GameCreator.ActionLibrary.Define(id);
            //   lib.DefineAction(actionid, kind, execution, question, func, code, args);
            //   ...
            //   GameCreator.Runtime.Script.Define("name", index, "code");
            //   ...
            //   obj = GameCreator.Runtime.Object.Define("name", index);
            //   ev = obj.DefineEvent(event, num);
            //   ev.DefineAction(libid, actionid, args, appliesto, relative, not);
            //   ...
            //   GameCreator.Runtime.Room.Define("name", index).CreationCode = "code";
            //   ...
            //   GameCreator.Runtime.Game.Name = "name";
            //   GameCreator.Runtime.Game.Run();
            //   (return)
            // }
            // GameCreator.Runtime.Object obj;
            // GameCreator.Runtime.Event ev;
            // GameCreator.Runtime.ActionLibrary lib;
            MethodBuilder initLibraries = program.DefineMethod("InitLibraries", MethodAttributes.Static);

            il = initLibraries.GetILGenerator();
            foreach (ActionLibrary lib in Program.Library)
            {
                // lib = GameCreator.ActionLibrary.Define(id);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                il.Emit(OpCodes.Ldc_I4, lib.LibraryID);
                il.EmitCall(OpCodes.Call, t_context.GetMethod("GetActionLibrary", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int) }, null), null);
                foreach (ActionDefinition ad in lib.Actions)
                {
                    // lib.DefineAction(actionid, kind, execution, question, func, code, args);
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldc_I4, ad.ActionID);
                    il.Emit(OpCodes.Ldc_I4, (int)ad.Kind);
                    il.Emit(OpCodes.Ldc_I4, (int)ad.ExecutionType);
                    il.Emit(ad.IsQuestion ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
                    il.Emit(OpCodes.Ldstr, ad.FunctionName);
                    il.Emit(OpCodes.Ldstr, ad.Code);
                    // ... , new ActionArgumentType[] { x, y, z },
                    il.Emit(OpCodes.Ldc_I4, ad.ArgumentCount);
                    il.Emit(OpCodes.Newarr, typeof(ActionArgumentType));
                    for (int i = 0; i < ad.ArgumentCount; i++)
                    {
                        il.Emit(OpCodes.Dup);
                        il.Emit(OpCodes.Ldc_I4, i);
                        il.Emit(OpCodes.Ldc_I4, (int)ad.Arguments[i].Type);
                        il.Emit(OpCodes.Stelem_I4);
                    }
                    //
                    il.EmitCall(OpCodes.Call, t_lib.GetMethod("DefineAction", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(ActionKind), typeof(ActionExecutionType), typeof(bool), typeof(string), typeof(string), typeof(ActionArgumentType[]) }, null), null);
                }
                il.Emit(OpCodes.Pop);
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder defineSprites = program.DefineMethod("DefineSprites", MethodAttributes.Static);

            il = defineSprites.GetILGenerator();
            foreach (SpriteResourceView res in Program.Sprites.Values)
            {
                // Define the resource
                int i = 0;
                foreach (Bitmap b in res.Animation.Frames)
                {
                    resw.AddResource(string.Format("spr_{0}_{1}", res.ResourceID, i++), b);
                }
                // GameCreator.Runtime.Sprite.Define("name", index, subimages);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Sprites", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.Emit(OpCodes.Ldstr, res.Name);
                il.Emit(OpCodes.Ldc_I4, res.ResourceID);
                il.Emit(OpCodes.Ldc_I4, res.Animation.FrameCount);
                il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Sprite>), typeof(string), typeof(int), typeof(int) }, null), null);
                il.Emit(OpCodes.Pop);
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder defineScripts = program.DefineMethod("DefineScripts", MethodAttributes.Static);

            il = defineScripts.GetILGenerator();
            foreach (ScriptResourceView res in Program.Scripts.Values)
            {
                // GameCreator.Runtime.Script.Define("name", index, "code");
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Sprites", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.Emit(OpCodes.Ldstr, res.Name);
                il.Emit(OpCodes.Ldc_I4, res.ResourceID);
                il.Emit(OpCodes.Ldstr, res.Code);
                il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Script>), typeof(string), typeof(int), typeof(string) }, null), null);
                il.Emit(OpCodes.Pop);
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder defineObjects = program.DefineMethod("DefineObjects", MethodAttributes.Static);

            il = defineObjects.GetILGenerator();
            foreach (ObjectResourceView res in Program.Objects.Values)
            {
                // obj = GameCreator.Runtime.Object.Define("name", index);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Objects", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                il.Emit(OpCodes.Ldstr, res.Name);
                il.Emit(OpCodes.Ldc_I4, res.ResourceID);
                il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Framework.Object>), typeof(string), typeof(int) }, null), null);
                foreach (ObjectEvent ev in res.Events)
                {
                    // ev = obj.DefineEvent(event, num);
                    il.Emit(OpCodes.Dup);
                    il.Emit(OpCodes.Ldc_I4, (int)ev.EventType);
                    il.Emit(OpCodes.Ldc_I4, (int)ev.EventNumber);
                    il.EmitCall(OpCodes.Call, t_obj.GetMethod("DefineEvent", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(int) }, null), null);
                    foreach (ActionDeclaration ad in ev.Actions)
                    {
                        // ev.DefineAction(libid, actionid, args, appliesto, relative, not);
                        il.Emit(OpCodes.Dup);
                        il.Emit(OpCodes.Ldc_I4, ad.Kind.Library.LibraryID);
                        il.Emit(OpCodes.Ldc_I4, ad.Kind.ActionID);
                        // ... , new string[] { "arg", "arg", "arg" },
                        il.Emit(OpCodes.Ldc_I4, ad.Kind.ArgumentCount);
                        il.Emit(OpCodes.Newarr, typeof(string));
                        for (int i = 0; i < ad.Kind.ArgumentCount; i++)
                        {
                            il.Emit(OpCodes.Dup);
                            il.Emit(OpCodes.Ldc_I4, i);
                            il.Emit(OpCodes.Ldstr, ad.Arguments[i]);
                            il.Emit(OpCodes.Stelem_Ref);
                        }
                        //
                        il.Emit(OpCodes.Ldc_I4, ad.AppliesTo);
                        il.Emit(ad.Relative ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
                        il.Emit(ad.Not ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
                        il.EmitCall(OpCodes.Call, t_event.GetMethod("DefineAction", BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(int), typeof(string[]), typeof(int), typeof(bool), typeof(bool) }, null), null);
                    }
                    il.Emit(OpCodes.Pop);
                }
                il.Emit(OpCodes.Dup);
                // obj.SpriteIndex = ind;
                il.Emit(OpCodes.Ldc_I4, res.Sprite);
                il.EmitCall(OpCodes.Call, t_obj.GetProperty("SpriteIndex").GetSetMethod(), null);
                //obj.Depth = d;
                il.Emit(OpCodes.Ldc_R8, res.Depth);
                il.EmitCall(OpCodes.Call, t_obj.GetProperty("Depth").GetSetMethod(), null);
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder defineRooms = program.DefineMethod("DefineRooms", MethodAttributes.Static);

            il = defineRooms.GetILGenerator();
            // Start defining rooms.
            // We perform a 'preorder iterative traversal' of the 'Rooms' TreeNode to ensure the rooms are defined in the correct order.
            // We can probably eliminate the stack by using the 'Parent' property of the nodes instead.
            Stack <TreeNode> nodes = new Stack <TreeNode>();

            nodes.Push(Rooms.Node);
            while (nodes.Count != 0)
            {
                TreeNode tn = nodes.Pop();
                if (tn.Tag.GetType() == typeof(RoomResourceView))
                {
                    RoomResourceView res = (RoomResourceView)(tn.Tag);
                    // GameCreator.Runtime.Room.Define("name", index).CreationCode = "code";
                    il.EmitCall(OpCodes.Call, t_context.GetProperty("Current", BindingFlags.Public | BindingFlags.Static).GetGetMethod(), null);
                    il.EmitCall(OpCodes.Call, t_context.GetProperty("Resources", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                    il.EmitCall(OpCodes.Call, t_rcontext.GetProperty("Rooms", BindingFlags.Public | BindingFlags.Instance).GetGetMethod(), null);
                    il.Emit(OpCodes.Ldstr, res.Name);
                    il.Emit(OpCodes.Ldc_I4, res.ResourceID);
                    il.EmitCall(OpCodes.Call, t_ext.GetMethod("Define", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IndexedResourceManager <Room>), typeof(string), typeof(int) }, null), null);
                    il.Emit(OpCodes.Ldstr, res.CreationCode);
                    il.EmitCall(OpCodes.Call, t_room.GetProperty("CreationCode").GetSetMethod(), null);
                }
                tn = tn.LastNode;
                while (tn != null)
                {
                    nodes.Push(tn);
                    tn = tn.PrevNode;
                }
            }
            il.Emit(OpCodes.Ret);
            MethodBuilder main = program.DefineMethod("Main", MethodAttributes.Static);

            main.SetCustomAttribute(new CustomAttributeBuilder(typeof(STAThreadAttribute).GetConstructor(System.Type.EmptyTypes), new object[] { }));
            il = main.GetILGenerator();
            // GameCreator.Runtime.Game.Interpreted.InterpretedGame.Initialize();
            il.EmitCall(OpCodes.Call, t_gamei.GetMethod("Initialize"), null);
            // InitLibraries();
            il.EmitCall(OpCodes.Call, initLibraries, null);
            // DefineScripts();
            il.EmitCall(OpCodes.Call, defineScripts, null);
            // DefineSprites();
            il.EmitCall(OpCodes.Call, defineSprites, null);
            // DefineObjects();
            il.EmitCall(OpCodes.Call, defineObjects, null);
            // DefineRooms();
            il.EmitCall(OpCodes.Call, defineRooms, null);
            // GameCreator.Runtime.Game.Name = "name";
            //il.Emit(OpCodes.Ldstr, asmname);
            //il.EmitCall(OpCodes.Call, t_game.GetProperty("Name").GetSetMethod(), null);
            // GameCreator.Runtime.Game.ResourceManager = GetResourceManager();
            il.EmitCall(OpCodes.Call, GetResourceManager, null);
            il.EmitCall(OpCodes.Call, t_game.GetProperty("ResourceManager").GetSetMethod(), null);
            // GameCreator.Runtime.Game.Interpreted.InterpretedGame.Run();
            il.EmitCall(OpCodes.Call, t_gamei.GetMethod("Run"), null);
            // return statement, required
            il.Emit(OpCodes.Ret);
            program.CreateType();
            asm.SetEntryPoint(main, PEFileKinds.WindowApplication);
            // Use 32 bit (i386) since GTK# requires it and we plan on using it later
            asm.Save(exename, PortableExecutableKinds.ILOnly, ImageFileMachine.I386);
            return(asm);
        }
Beispiel #49
0
        public static void Main()
        {
            // An assembly consists of one or more modules, each of which
            // contains zero or more types. This code creates a single-module
            // assembly, the most common case. The module contains one type,
            // named "MyDynamicType", that has a private field, a property
            // that gets and sets the private field, constructors that
            // initialize the private field, and a method that multiplies
            // a user-supplied number by the private field value and returns
            // the result. In C# the type might look like this:

            /*
             * public class MyDynamicType
             * {
             *      private int m_number;
             *
             *      public MyDynamicType() : this(42) {}
             *      public MyDynamicType(int initNumber)
             *      {
             *              m_number = initNumber;
             *      }
             *
             *      public int Number
             *      {
             *              get { return m_number; }
             *              set { m_number = value; }
             *      }
             *
             *      public int MyMethod(int multiplier)
             *      {
             *              return m_number * multiplier;
             *      }
             * }
             */

            AssemblyName aName = new AssemblyName("DynamicAssemblyExample");

            System.Reflection.Emit.AssemblyBuilder ab =
                AppDomain.CurrentDomain.DefineDynamicAssembly(
                    aName,
                    AssemblyBuilderAccess.RunAndSave);

            // For a single-module assembly, the module name is usually
            // the assembly name plus an extension.
            ModuleBuilder mb =
                ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");

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

            // Add a private field of type int (Int32).
            FieldBuilder fbNumber = tb.DefineField(
                "m_number",
                typeof(int),
                FieldAttributes.Private);

            // Define a constructor that takes an integer argument and
            // stores it in the private field.
            Type[]             parameterTypes = { typeof(int) };
            ConstructorBuilder ctor1          = tb.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                parameterTypes);

            ILGenerator ctor1IL = ctor1.GetILGenerator();

            // For a constructor, argument zero is a reference to the new
            // instance. Push it on the stack before calling the base
            // class constructor. Specify the default constructor of the
            // base class (System.Object) by passing an empty array of
            // types (Type.EmptyTypes) to GetConstructor.
            ctor1IL.Emit(OpCodes.Ldarg_0);
            ctor1IL.Emit(OpCodes.Call,
                         typeof(object).GetConstructor(Type.EmptyTypes));
            // Push the instance on the stack before pushing the argument
            // that is to be assigned to the private field m_number.
            ctor1IL.Emit(OpCodes.Ldarg_0);
            ctor1IL.Emit(OpCodes.Ldarg_1);
            ctor1IL.Emit(OpCodes.Stfld, fbNumber);
            ctor1IL.Emit(OpCodes.Ret);

            // Define a default constructor that supplies a default value
            // for the private field. For parameter types, pass the empty
            // array of types or pass null.
            ConstructorBuilder ctor0 = tb.DefineConstructor(
                MethodAttributes.Public,
                CallingConventions.Standard,
                Type.EmptyTypes);

            ILGenerator ctor0IL = ctor0.GetILGenerator();

            // For a constructor, argument zero is a reference to the new
            // instance. Push it on the stack before pushing the default
            // value on the stack, then call constructor ctor1.
            ctor0IL.Emit(OpCodes.Ldarg_0);
            ctor0IL.Emit(OpCodes.Ldc_I4_S, 42);
            ctor0IL.Emit(OpCodes.Call, ctor1);
            ctor0IL.Emit(OpCodes.Ret);

            // Define a property named Number that gets and sets the private
            // field.
            //
            // The last argument of DefineProperty is null, because the
            // property has no parameters. (If you don't specify null, you must
            // specify an array of Type objects. For a parameterless property,
            // use the built-in array with no elements: Type.EmptyTypes)
            PropertyBuilder pbNumber = tb.DefineProperty(
                "Number",
                PropertyAttributes.HasDefault,
                typeof(int),
                null);

            // The property "set" and property "get" methods require a special
            // set of attributes.
            MethodAttributes getSetAttr = MethodAttributes.Public |
                                          MethodAttributes.SpecialName | MethodAttributes.HideBySig;

            // Define the "get" accessor method for Number. The method returns
            // an integer and has no arguments. (Note that null could be
            // used instead of Types.EmptyTypes)
            MethodBuilder mbNumberGetAccessor = tb.DefineMethod(
                "get_Number",
                getSetAttr,
                typeof(int),
                Type.EmptyTypes);

            ILGenerator numberGetIL = mbNumberGetAccessor.GetILGenerator();

            // For an instance property, argument zero is the instance. Load the
            // instance, then load the private field and return, leaving the
            // field value on the stack.
            numberGetIL.Emit(OpCodes.Ldarg_0);
            numberGetIL.Emit(OpCodes.Ldfld, fbNumber);
            numberGetIL.Emit(OpCodes.Ret);

            // Define the "set" accessor method for Number, which has no return
            // type and takes one argument of type int (Int32).
            MethodBuilder mbNumberSetAccessor = tb.DefineMethod(
                "set_Number",
                getSetAttr,
                null,
                new Type[] { typeof(int) });

            ILGenerator numberSetIL = mbNumberSetAccessor.GetILGenerator();

            // Load the instance and then the numeric argument, then store the
            // argument in the field.
            numberSetIL.Emit(OpCodes.Ldarg_0);
            numberSetIL.Emit(OpCodes.Ldarg_1);
            numberSetIL.Emit(OpCodes.Stfld, fbNumber);
            numberSetIL.Emit(OpCodes.Ret);

            // Last, map the "get" and "set" accessor methods to the
            // PropertyBuilder. The property is now complete.
            pbNumber.SetGetMethod(mbNumberGetAccessor);
            pbNumber.SetSetMethod(mbNumberSetAccessor);

            // Define a method that accepts an integer argument and returns
            // the product of that integer and the private field m_number. This
            // time, the array of parameter types is created on the fly.
            MethodBuilder meth = tb.DefineMethod(
                "MyMethod",
                MethodAttributes.Public,
                typeof(int),
                new Type[] { typeof(int) });

            ILGenerator methIL = meth.GetILGenerator();

            // To retrieve the private instance field, load the instance it
            // belongs to (argument zero). After loading the field, load the
            // argument one and then multiply. Return from the method with
            // the return value (the product of the two numbers) on the
            // execution stack.
            methIL.Emit(OpCodes.Ldarg_0);
            methIL.Emit(OpCodes.Ldfld, fbNumber);
            methIL.Emit(OpCodes.Ldarg_1);
            methIL.Emit(OpCodes.Mul);
            methIL.Emit(OpCodes.Ret);

            // Finish the type.
            Type t = tb.CreateType();

            // The following line saves the single-module assembly. This
            // requires AssemblyBuilderAccess to include Save. You can now
            // type "ildasm MyDynamicAsm.dll" at the command prompt, and
            // examine the assembly. You can also write a program that has
            // a reference to the assembly, and use the MyDynamicType type.
            //
            ab.Save(aName.Name + ".dll");

            // Because AssemblyBuilderAccess includes Run, the code can be
            // executed immediately. Start by getting reflection objects for
            // the method and the property.
            MethodInfo   mi = t.GetMethod("MyMethod");
            PropertyInfo pi = t.GetProperty("Number");

            // Create an instance of MyDynamicType using the default
            // constructor.
            object o1 = Activator.CreateInstance(t);

            // Display the value of the property, then change it to 127 and
            // display it again. Use null to indicate that the property
            // has no index.
            Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null));
            pi.SetValue(o1, 127, null);
            Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null));

            // Call MyMethod, passing 22, and display the return value, 22
            // times 127. Arguments must be passed as an array, even when
            // there is only one.
            object[] arguments = { 22 };
            Console.WriteLine("o1.MyMethod(22): {0}",
                              mi.Invoke(o1, arguments));

            // Create an instance of MyDynamicType using the constructor
            // that specifies m_Number. The constructor is identified by
            // matching the types in the argument array. In this case,
            // the argument array is created on the fly. Display the
            // property value.
            object o2 = Activator.CreateInstance(t,
                                                 new object[] { 5280 });

            Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, null));
        }
        public T BuildAssemblyFromType <T>(Type type, Object [] args)
        {
            Object[] assemblyAndType = GetAssemblyForType(type);

            if (assemblyAndType != null)
            {
                return(CreateInstance <T>((System.Reflection.Emit.AssemblyBuilder)assemblyAndType[0], assemblyAndType[1].ToString(), args));
            }

            AppDomain    domain = Thread.GetDomain();
            AssemblyName name   = new AssemblyName(Utilities.RandomString.Generate());

            System.Reflection.Emit.AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(name, System.Reflection.Emit.AssemblyBuilderAccess.Run);
            ModuleBuilder modBuilder  = assemblyBuilder.DefineDynamicModule(name.Name, true);
            string        newTypeName = type.Name + "_" + (_guid++);
            TypeBuilder   typeBuilder = modBuilder.DefineType(newTypeName, new TypeAttributes(), type);

            FieldBuilder memberField = null;

            foreach (MethodInfo method in type.GetMethods())
            {
                if (method.IsAbstract && !method.IsSpecialName)
                {
                    memberField = BuildDiscreteMethod(typeBuilder, method);

                    MethodBuilder overrideBody = GetMethodOverride(typeBuilder, method, memberField);
                    typeBuilder.DefineMethodOverride(overrideBody, method);
                }
            }
            foreach (PropertyInfo propertyInfo in type.GetProperties())
            {
                if ((propertyInfo.CanRead && propertyInfo.GetGetMethod().IsAbstract) || (propertyInfo.CanWrite && propertyInfo.GetSetMethod().IsAbstract))
                {
                    memberField = CreateMemberField(typeBuilder, propertyInfo);
                    typeBuilder.DefineProperty(propertyInfo.Name,
                                               PropertyAttributes.HasDefault,
                                               propertyInfo.PropertyType,
                                               null);
                    if (propertyInfo.CanRead)
                    {
                        GetGetMethodBuilderFromProperty(typeBuilder, propertyInfo, memberField);
                    }

                    if (propertyInfo.CanWrite)
                    {
                        GetSetMethodBuilderFromProperty(typeBuilder, propertyInfo, memberField);
                    }
                    else
                    {
                        typeBuilder.DefineProperty("__" + propertyInfo.Name,
                                                   PropertyAttributes.HasDefault,
                                                   propertyInfo.PropertyType,
                                                   null);
                        GetDiscreteSetMethodBuilderFromProperty(typeBuilder, propertyInfo, memberField);
                    }
                }
            }

            Type newType = typeBuilder.CreateType();

            //cache it
            assemblyAndType    = new Object[2];
            assemblyAndType[0] = assemblyBuilder;
            assemblyAndType[1] = newType.FullName;
            assemblyCache.Add(type, assemblyAndType);

            return(CreateInstance <T>(assemblyBuilder, newType.FullName, args));
        }