namespace Cecil.Debug { using System; using System.IO; using SR = System.Reflection; using Mono.Cecil; using Mono.Cecil.Cil; public class Create { static void CMain () { AssemblyDefinition asm = AssemblyFactory.DefineAssembly ("Hello", AssemblyKind.Console); TypeDefinition prog = new TypeDefinition ("Program", string.Empty, TypeAttributes.Public, asm.MainModule.Import (typeof (object))); prog.Attributes |= TypeAttributes.BeforeFieldInit; MethodDefinition ctor = new MethodDefinition (MethodDefinition.Ctor, MethodAttributes.Public, asm.MainModule.Import (typeof (void))); ctor.Attributes |= MethodAttributes.SpecialName; ctor.Attributes |= MethodAttributes.RTSpecialName; ctor.Attributes |= MethodAttributes.HideBySig; ctor.Body.CilWorker.Emit (OpCodes.Ldarg_0); ctor.Body.CilWorker.Emit (OpCodes.Call, asm.MainModule.Import (typeof (object).GetConstructor (new Type [0]))); ctor.Body.CilWorker.Emit (OpCodes.Ret); prog.Constructors.Add (ctor); MethodDefinition hello = new MethodDefinition ("Hello", MethodAttributes.Public, asm.MainModule.Import (typeof (void))); hello.Attributes |= MethodAttributes.HideBySig; hello.Body.CilWorker.Emit (OpCodes.Ldstr, "Hello World !"); hello.Body.CilWorker.Emit (OpCodes.Call, asm.MainModule.Import (typeof (Console).GetMethod ("WriteLine", new Type [] { typeof (string) }))); hello.Body.CilWorker.Emit (OpCodes.Ret); prog.Methods.Add (hello); MethodDefinition main = new MethodDefinition ("Main", MethodAttributes.Public | MethodAttributes.Static, asm.MainModule.Import (typeof (void))); main.Body.CilWorker.Emit (OpCodes.Newobj, ctor); main.Body.CilWorker.Emit (OpCodes.Call, hello); main.Body.CilWorker.Emit (OpCodes.Ret); prog.Methods.Add (main); asm.EntryPoint = main; asm.MainModule.Types.Add (prog); MemoryStream ms = new MemoryStream (); AssemblyFactory.SaveAssembly (asm, ms); SR.Assembly srasm = SR.Assembly.Load (ms.ToArray ()); //SR.Assembly srasm = AssemblyFactory.CreateReflectionAssembly (asm); Type tprog = srasm.GetType ("Program"); Console.WriteLine (tprog.FullName); object inst = Activator.CreateInstance (tprog); tprog.GetMethod ("Hello").Invoke (inst, new object [0]); Console.Read (); } } }