Inheritance: System.Reflection.Assembly, _AssemblyBuilder
Beispiel #1
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);
 }
        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;
        }
Beispiel #3
0
 static MethodInvoker(){
   MethodInvoker.invokerFor = new SimpleHashtable(64);
   AssemblyName name = new AssemblyName();
   name.Name = "JScript MethodInvoker Assembly";
   MethodInvoker.assembly = Thread.GetDomain().DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
   MethodInvoker.module = MethodInvoker.assembly.DefineDynamicModule("JScript MethodInvoker Module");
 }
 /// <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");
 }
         /// <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);
            }
        }
 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 #7
0
 public void Reset()
 {
     UniqueCounter++;
     var CurrentAppDomain = AppDomain.CurrentDomain;
     AssemblyBuilder = CurrentAppDomain.DefineDynamicAssembly(new AssemblyName("assembly" + UniqueCounter), AssemblyBuilderAccess.RunAndSave);
     ModuleBuilder = AssemblyBuilder.DefineDynamicModule("module" + UniqueCounter);
 }
 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 #9
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 #10
0
		internal ModuleBuilder (AssemblyBuilder assb, string name, string fullyqname, bool emitSymbolInfo, bool transient) {
			this.name = this.scopename = name;
			this.fqname = fullyqname;
			this.assembly = this.assemblyb = assb;
			this.transient = transient;
			// to keep mcs fast we do not want CryptoConfig wo be involved to create the RNG
			guid = Guid.FastNewGuidArray ();
			// guid = Guid.NewGuid().ToByteArray ();
			table_idx = get_next_table_index (this, 0x00, true);
			name_cache = new Dictionary<TypeName, TypeBuilder> ();
			us_string_cache = new Dictionary<string, int> (512);

			basic_init (this);

			CreateGlobalType ();

			if (assb.IsRun) {
				TypeBuilder tb = new TypeBuilder (this, TypeAttributes.Abstract, 0xFFFFFF); /*last valid token*/
				Type type = tb.CreateType ();
				set_wrappers_type (this, type);
			}

			if (emitSymbolInfo) {
				Assembly asm = Assembly.LoadWithPartialName ("Mono.CompilerServices.SymbolWriter");
				if (asm == null)
					throw new TypeLoadException ("The assembly for default symbol writer cannot be loaded");

				Type t = asm.GetType ("Mono.CompilerServices.SymbolWriter.SymbolWriterImpl", true);
				symbolWriter = (ISymbolWriter) Activator.CreateInstance (t, new object[] { this });
				string fileName = fqname;
				if (assemblyb.AssemblyDir != null)
					fileName = Path.Combine (assemblyb.AssemblyDir, fileName);
				symbolWriter.Initialize (IntPtr.Zero, fileName, true);
			}
		}
Beispiel #11
0
        private static void SaveAssembly(string fullPath, AssemblyBuilder assemblyBuilder)
        {
            // assemblyBuilder.Save doesn't want to save with full path, so saving to current directory and then
            // moving file to final, weird
            string fileName = Path.GetFileName(fullPath);

            if (File.Exists(fileName))
            {
                File.Delete(fullPath);
            }

            assemblyBuilder.Save(fileName);

            if (fileName != fullPath)
            {
                string targetDirectory = Path.GetDirectoryName(fullPath);
                Debug.Assert(targetDirectory != null, "targetDirectory != null");
                Directory.CreateDirectory(targetDirectory);
                Debug.Assert(fileName != null, "fileName != null");

                if (!File.Exists(fullPath))
                {
                    File.Move(fileName, fullPath);
                }
            }
        }
 internal RegexTypeCompiler(AssemblyName an, CustomAttributeBuilder[] attribs, string resourceFile)
 {
     new ReflectionPermission(PermissionState.Unrestricted).Assert();
     try
     {
         List<CustomAttributeBuilder> assemblyAttributes = new List<CustomAttributeBuilder>();
         CustomAttributeBuilder item = new CustomAttributeBuilder(typeof(SecurityTransparentAttribute).GetConstructor(Type.EmptyTypes), new object[0]);
         assemblyAttributes.Add(item);
         CustomAttributeBuilder builder2 = new CustomAttributeBuilder(typeof(SecurityRulesAttribute).GetConstructor(new Type[] { typeof(SecurityRuleSet) }), new object[] { SecurityRuleSet.Level2 });
         assemblyAttributes.Add(builder2);
         this._assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave, assemblyAttributes);
         this._module = this._assembly.DefineDynamicModule(an.Name + ".dll");
         if (attribs != null)
         {
             for (int i = 0; i < attribs.Length; i++)
             {
                 this._assembly.SetCustomAttribute(attribs[i]);
             }
         }
         if (resourceFile != null)
         {
             this._assembly.DefineUnmanagedResource(resourceFile);
         }
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
     }
 }
Beispiel #13
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 #14
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 #15
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;
        }
Beispiel #16
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 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 EmittedAssembly(string name, string rootNamespace, Version version, CultureInfo culture
			, byte[] publicKey, byte[] publicKeyToken)
        {
            Contracts.Require.IsNotNull("name", name);
            Contracts.Require.IsNotEmpty("name", name);
            Contracts.Require.IsNotNull("rootNamespace", rootNamespace);
            Contracts.Require.IsNotEmpty("rootNamespace", name);
            Contracts.Require.IsNotNull("version", version);
            Contracts.Require.IsNotNull("culture", culture);

            this._classes = new Dictionary<string, EmittedClass>();
            this.RootNamespace = rootNamespace ?? name;
            _assemName = new AssemblyName(name);
            _assemName.Version = version;
            _assemName.CultureInfo = culture;
            _assemName.SetPublicKey(publicKey);
            _assemName.SetPublicKeyToken(publicKeyToken);
            #if DEBUG
            this._assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemName, AssemblyBuilderAccess.RunAndSave);
            this._module = this._assembly.DefineDynamicModule(name, name + ".dll", false);
            #else
            this._assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(_assemName, AssemblyBuilderAccess.Run);
            this._module = this._assembly.DefineDynamicModule(name, name + ".dll", false);
            #endif
        }
Beispiel #19
0
 public RedisTypes(AssemblyBuilder assemblyBuilder, string assemblyFileName, Type redisType, Type redisPipelneType)
 {
     this.Assembly = assemblyBuilder;
     this.AssemblyFileName = assemblyFileName;
     this.RedisType = redisType;
     this.RedisPipelineType = redisPipelneType;
 }
Beispiel #20
0
 static FieldAccessor(){
   FieldAccessor.accessorFor = new SimpleHashtable(32);
   AssemblyName name = new AssemblyName();
   name.Name = "JScript FieldAccessor Assembly";
   FieldAccessor.assembly = Thread.GetDomain().DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
   FieldAccessor.module = FieldAccessor.assembly.DefineDynamicModule("JScript FieldAccessor Module");
 }
Beispiel #21
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);
            }
        }
Beispiel #22
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);
 }
 private void CreateCallee()
 {
     AssemblyName myAssemblyName = new AssemblyName();
     myAssemblyName.Name = "EnumAssembly";
     _myAssemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run);
     _myModuleBuilder = TestLibrary.Utilities.GetModuleBuilder(_myAssemblyBuilder, "EnumModule.mod");
 }
Beispiel #24
0
 public static void Clear()
 {
     _dynamicAssembly = null;
     _moduleBuilder = null;
     _typeBuilder = null;
     _accessorList.Clear();
 }
        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
        }
		public AssemblyAlgorithmIdAttributeTest ()
		{
			//create a dynamic assembly with the required attribute
			//and check for the validity

			dynAsmName.Name = "TestAssembly";

			dynAssembly = Thread.GetDomain ().DefineDynamicAssembly (
				dynAsmName,AssemblyBuilderAccess.Run
				);

			// Set the required Attribute of the assembly.
			Type attribute = typeof (AssemblyAlgorithmIdAttribute);
			ConstructorInfo ctrInfo = attribute.GetConstructor (
				new Type [] { typeof (AssemblyHashAlgorithm) }
				);
			CustomAttributeBuilder attrBuilder =
				new CustomAttributeBuilder (
				ctrInfo,
				new object [1] { AssemblyHashAlgorithm.MD5 }
				);
			dynAssembly.SetCustomAttribute (attrBuilder);
			object [] attributes = dynAssembly.GetCustomAttributes (true);
			attr = attributes [0] as AssemblyAlgorithmIdAttribute;
		}
Beispiel #27
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 #28
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>();
 }
        /// <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");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EmitPropertyGetAccessor"/> class.
        /// </summary>
        /// <param name="targetObjectType">Type of the target object.</param>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="assemblyBuilder">The <see cref="AssemblyBuilder"/>.</param>
        /// <param name="moduleBuilder">The <see cref="ModuleBuilder"/>.</param>
        public EmitPropertyGetAccessor(Type targetObjectType, string propertyName, AssemblyBuilder assemblyBuilder, ModuleBuilder moduleBuilder)
        {
            _targetType = targetObjectType;
            _propertyName = propertyName;

            // deals with Overriding a property using new and reflection
            // http://blogs.msdn.com/thottams/archive/2006/03/17/553376.aspx
            PropertyInfo propertyInfo = _targetType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            if (propertyInfo == null)
            {
                propertyInfo = _targetType.GetProperty(propertyName);
            }

            // Make sure the property exists
            if(propertyInfo == null)
            {
                throw new NotSupportedException(
                    string.Format("Property \"{0}\" does not exist for type "
                    + "{1}.", propertyName, _targetType));
            }
            else
            {
                this._propertyType = propertyInfo.PropertyType;
                _canRead = propertyInfo.CanRead;
                this.EmitIL(assemblyBuilder, moduleBuilder);
            }
        }
        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);
            }
        }
        /// <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);
        }
Beispiel #33
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 #34
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 #35
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 #36
0
 private static void basic_init(AssemblyBuilder ab)
 {
     throw new System.NotImplementedException();
 }
Beispiel #37
0
 private Module nGetInMemoryAssemblyModule()
 {
     return(AssemblyBuilder.GetInMemoryAssemblyModule(GetNativeHandle()));
 }
Beispiel #38
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));
        }
Beispiel #39
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);
        }
 public void SetBaseTypeConstraint([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type?baseTypeConstraint)
 {
     AssemblyBuilder.CheckContext(baseTypeConstraint);
     m_type.SetParent(baseTypeConstraint);
 }
 public void SetInterfaceConstraints(params Type[]?interfaceConstraints)
 {
     AssemblyBuilder.CheckContext(interfaceConstraints);
     m_type.SetInterfaces(interfaceConstraints);
 }
 private static extern void basic_init(AssemblyBuilder ab);
 private static extern void UpdateNativeCustomAttributes(AssemblyBuilder ab);
Beispiel #44
0
        public void SetReturnType(Type?returnType)
        {
            AssemblyBuilder.CheckContext(returnType);

            SetSignature(returnType, null, null, null, null, null);
        }
Beispiel #45
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);
        }
        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));
        }
Beispiel #47
0
        public void SetParameters(params Type[] parameterTypes)
        {
            AssemblyBuilder.CheckContext(parameterTypes);

            SetSignature(null, null, null, parameterTypes, null, null);
        }
 private T CreateInstance <T>(System.Reflection.Emit.AssemblyBuilder assembly, string className, Object[] args)
 {
     return((T)assembly.CreateInstance(className, false, BindingFlags.CreateInstance, null, args, null, null));
 }
Beispiel #49
0
        public void CreateAssembly()
        {
            // we need to process global assembly attributes before creating assembly name
            _assembly_name = CreateAssemblyName();

            _assembly_name.Name = Path.GetFileNameWithoutExtension(_OutputFileName);

            var assembly_requirements =
                (Manager.Options.CompileToMemory)
                    ? Emit.AssemblyBuilderAccess.Run
                    : Emit.AssemblyBuilderAccess.Save;

            var dir = Path.GetDirectoryName(Path.GetFullPath(_OutputFileName));
            if (!Directory.Exists(dir))
                Message.FatalError($"specified output directory `$dir' does not exist");

            PermissionSet required;
            PermissionSet optional;
            PermissionSet refused;

            foreach ((action, perm_set) in Manager.AttributeCompiler.GetPermissionSets(assembly_attributes))
            {
                switch (action)
                {
                    case Permissions.SecurityAction.RequestMinimum:
                        required = perm_set;
                        break;
                    case Permissions.SecurityAction.RequestOptional:
                        optional = perm_set;
                        break;
                    case Permissions.SecurityAction.RequestRefuse:
                        refused = perm_set;
                        break;
                    default:
                        Message.FatalError($"$action is not valid here");
                        break;
                }
            }

            /* define a dynamic assembly */
            this._assembly_builder =
                System.AppDomain.CurrentDomain.DefineDynamicAssembly
                (this._assembly_name,
                    assembly_requirements,
                    dir, required, optional, refused);

            GetInformationalAssemblyAttributes().Iter(this._assembly_builder.SetCustomAttribute);

            if (_assembly_name.Name == "")
                Message.FatalError("name of output assembly cannot be empty");

            /* create a dynamic module */
            this._module_builder =
                (Manager.Options.CompileToMemory)
                    // we cannot give output filename if we are compiling only to Run
                    ? this._assembly_builder.DefineDynamicModule(_assembly_name.Name, Manager.Options.EmitDebug)
                    : this._assembly_builder.DefineDynamicModule(_assembly_name.Name,
                        Path.GetFileName(_OutputFileName),
                        Manager.Options.EmitDebug);

            if (Manager.Options.EmitDebug)
                _debug_emit = _module_builder.GetSymWriter();
        }