编译时MSIL注入--实践Mono Cecil(1)
? 緊接上兩篇淺談.NET編譯時注入(C#-->IL)和淺談VS編譯自定義編譯任務—MSBuild Task(csproject),在第一篇中我們簡單研究了c#語法糖和PostSharp的MSIl注入,緊接第二篇中我們介紹了自定義MSBuild編譯任務(記得有位老兄發鏈接用 MSBuild自動發布Silverlight xap ,我想說的我做的是自定義編譯任務,不是什么發布,MSBuild本就是一個發布工具)。之所以在此前介紹編譯Task是因為我講介紹的就是利用MSBuild和MSILInject制作靜態注入式AOP,想成熟的產品PostSharp,當然我也不會去重造輪子,但需要明白起原理和自動化注入時機。廢話不多說,今天將請出我們的MSIL注入的好東西:Mono.Cecil.官方網站http://www.mono-project.com/Cecil,他是一個強大的MSIL 注入工具,在我們的Reflector插件Reflexil(動態修改程序集插件,很好用,我已經嘗試多次)就有他的身影出現。還有如大名鼎鼎的SharpDevelop,LINQPad,Ja.NET等等(可以參見https://github.com/jbevain/cecil/wiki/Users)。
????? 在本節我們需要看看這個Mono.Cecil,先來一個簡單的認識。
我來在我們的方法執行前后加入我們的輸出信息:
原來代碼:
class?Program????{?
???????static?void?Main(string[]?args)?
???????{?
???????????Console.WriteLine("破浪Blog:http://www.cnblogs.com/whitewolf/");?
???????}?
???}
任務:
1我將在方法執行前后添加一個Console.WriteLine("Method start…");
2方法最后添加Console.WriteLine("Method finish…“);
具體Mono.Cecil Code:
using?System;?using?System.Collections.Generic;?
using?System.Linq;?
using?System.Text;?
using?Mono.Cecil;?
using?Mono.Cecil.Cil;?
namespace?BlogSample?
{?
????class?Program?
????{?
????????static?void?Main(string[]?args)?
????????{?
????????????AssemblyDefinition?assembiy?=?AssemblyFactory.GetAssembly(args[0]);?
????????????foreach?(Mono.Cecil.TypeDefinition?item?in?assembiy.MainModule.Types)?
????????????{?
????????????????foreach?(MethodDefinition?method?in?item.Methods)?
????????????????{?
????????????????????if?(method.Name.Equals("Main"))?
????????????????????{?
????????????????????????var?ins?=?method.Body.Instructions[0];?
????????????????????????var?worker?=?method.Body.CilWorker;?
????????????????????????worker.InsertBefore(ins,?worker.Create(OpCodes.Ldstr,?"Method?start…"));?
????????????????????????worker.InsertBefore(ins,?worker.Create(OpCodes.Call,?
????????????????????????????assembiy.MainModule.Import(typeof(Console).GetMethod("WriteLine",?new?Type[]?{?typeof(string)?}))));?
????????????????????????ins?=?method.Body.Instructions[method.Body.Instructions.Count?-?1];?
????????????????????????worker.InsertBefore(ins,?worker.Create(OpCodes.Ldstr,?"Method?finish…"));?
????????????????????????worker.InsertBefore(ins,?worker.Create(OpCodes.Call,?
????????????????????????????assembiy.MainModule.Import(typeof(Console).GetMethod("WriteLine",?new?Type[]?{?typeof(string)?}))));?
????????????????????????break;?
????????????????????}?
????????????????}?
????????????}?
????????????AssemblyFactory.SaveAssembly(assembiy,?"IL_"?+?args[0]);?
????????????Console.Read();?
????????}?
????}?
}
DOS運行結果:
我們在來看看反編譯后的MSIL
C#:
??? 在這最后我們可以想一下,如果我們利用Mono.Cecil可以干些什么事情,能做的當然很多,我首先想嘗試的了與上一節淺談VS編譯自定義編譯任務—MSBuild Task(csproject)結合PostSharp一樣的靜態注入AOP框架。還能做什么的就要靠大家發揮大家聰明的才智。
本文轉自破狼博客園博客,原文鏈接:http://www.cnblogs.com/whitewolf/archive/2011/07/28/2119969.html,如需轉載請自行聯系原作者
總結
以上是生活随笔為你收集整理的编译时MSIL注入--实践Mono Cecil(1)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在CENTOS7下安装kubernete
- 下一篇: 操作系统结构