ã¯ããã¦ã®Cecil
Cecil is a library written by Jb Evain (http://evain.net/blog/) to generate and inspect programs and libraries in the ECMA CIL format. It has full support for generics, and support some debugging symbol format.
ILãã¤ããªããã«ããã«ãããããåããã©ã¤ãã©ãªã§ããMono meetingã§ããååãèãã¦ãã¾ããã使ã£ããã¨ãç¡ãã£ãã®ã§è©¦ãã¦ã¿ã¾ããã
ãµã³ãã«ã³ã¼ããã¡ãã£ã¨ã ãæ¹å¤ãããã®ã³ã°ã³ã¼ããåãè¾¼ãä¾ã(ãã¤ããªæ¸ãæãAOPã£ã½ããã¤)
using System; using Mono.Cecil; using Mono.Cecil.Cil; using System.Reflection; class Program { // ã¡ã½ããå¼ã³åºãã®ãã°å¦çãåãè¾¼ã static void Logging (AssemblyDefinition assembly,TypeDefinition type) { MethodInfo miWriteLine = typeof (Console).GetMethod ("WriteLine",new { typeof (string),typeof (object) }); MethodInfo miNow = typeof (DateTime).GetMethod ("get_Now",new Type[0]); // åã«å±ããå ¨ã¦ã®ã¡ã½ãããæ¸ãæãã foreach (MethodDefinition method in type.Methods) { CilWorker worker = method.Body.CilWorker; // Console.WriterLineã¨DateTime.Nowã使ã MethodReference writeLine; writeLine = assembly.MainModule.Import (miWriteLine); MethodReference now; now = assembly.MainModule.Import (miNow); // 以ä¸ã®ã³ã¼ããåã¡ã½ããã®å é ã«å²ãè¾¼ã¾ãã // Console.WriteLine ("in methodName at {0}.", DateTime.Now); Instruction ldstr = worker.Create (OpCodes.Ldstr,"in " + method.Name + " at {0}."); Instruction callNow = worker.Create (OpCodes.Call,now); Instruction box = worker.Create (OpCodes.Box,assembly.MainModule.Import (typeof (DateTime))); Instruction callWriteLine = worker.Create (OpCodes.Call,writeLine); // ã¡ã½ããã®å é Instruction ins = method.Body.Instructions[0]; // WriteLineã«æ¸¡ãæååãã¹ã¿ãã¯ã«ç©ã worker.InsertBefore (ins,ldstr); // DateTime.Nowãå¼ã³åºã worker.InsertAfter (ldstr,callNow); // æ»ãå¤ã®DateTimeãboxå worker.InsertAfter (callNow,box); // Console.WriteLineãå¼ã³åºã worker.InsertAfter (box,callWriteLine); } // å¤æ´ããåãã¤ã³ãã¼ã assembly.MainModule.Import (type); } static void Main (string args) { if (args.Length == 0) return; // pathã¯æ¸ãæããã¢ã»ã³ããªã®ãã¹ string path = args[0]; AssemblyDefinition asm = AssemblyFactory.GetAssembly (path); foreach (TypeDefinition type in asm.MainModule.Types) Logging (asm,type); // ã¢ã»ã³ããªã®ä¿å // æ¬å½ã«exe/dllãæ¸ãæããã®ã§ãã¹ãããå ´åã¯ãããã¯ã¢ãããåã£ã¦ããã㨠AssemblyFactory.SaveAssembly (asm,path); } } /* çµæ in Main at 2008/09/23 17:09:02. in set_Greeting at 2008/09/23 17:09:02. in Run at 2008/09/23 17:09:02. in get_Greeting at 2008/09/23 17:09:02. */
Reflection.Emitã¨éã£ã¦å¼ããããã³ã¼ããAppDomainã«èªã¿è¾¼ã¾ãªãã¦ãããã¿ããã§ãããä»ã«ããããã°ã·ã³ãã«ã«ã¢ã¯ã»ã¹ãããè²ã åºæ¥ãããªæãã§ãããããã¥ã¡ã³ããå°ãªãããã½ã¼ã¹ã³ã¼ããèªãå¿ è¦ããããã(^^;