最近一直在學習Emit,對指令有一些瞭解.總結了一些小經驗在IL指令中經常的事情就
是把變數,參數推到堆棧上然後call一些方法,來來回回的這樣做.下面貼個用DynamicMethod簡單實現方法的代碼:)
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DynamicMethod dm = new DynamicMethod("Test", null,
new Type[] { typeof( string) },typeof(string).Module);
ILGenerator il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);//把參數推到堆棧上
MethodInfo call = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string)});
il.Emit(OpCodes.Call, call);//執行Console.WriteLine方法
il.Emit(OpCodes.Ret);//結束返回
Action<string> test = (Action<string>)dm.CreateDelegate(typeof(Action<string>));
test("henry");
//下面Test1方法和Test完成的方法是一樣的,但IL似乎有些不同.
//主要體現變數設定,對於變數的位置也會影響指令
dm = new DynamicMethod("Test1", null,
new Type[] { typeof(string) }, typeof(string).Module);
il = dm.GetILGenerator();
il.DeclareLocal(typeof(string));
il.Emit(OpCodes.Ldarg_0);//把參數推到堆棧上
il.Emit(OpCodes.Stloc_0);//把值儲存到索引為0的變數裡
il.Emit(OpCodes.Ldloc_0);//把索引為0的變數推到堆棧上
call = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
il.Emit(OpCodes.Call, call);//執行Console.WriteLine方法
il.Emit(OpCodes.Ret);
test = (Action<string>)dm.CreateDelegate(typeof(Action<string>));
test("henry");
//對於下面的方法大家自己推一下,其實很簡單.
//如果看起來有不明白,不防copy到vs.net上然後看指令描述資訊:)
dm = new DynamicMethod("Test2", null,
new Type[] { typeof(string) }, typeof(string).Module);
il = dm.GetILGenerator();
il.DeclareLocal(typeof(string));
il.Emit(OpCodes.Ldstr, "你好 ");
il.Emit(OpCodes.Ldarg_0);
call = typeof(string).GetMethod("Concat", new Type[] {typeof(string),typeof(string) });
il.Emit(OpCodes.Call, call);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloc_0);
call = typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) });
il.Emit(OpCodes.Call, call);
il.Emit(OpCodes.Ret);
test = (Action<string>)dm.CreateDelegate(typeof(Action<string>));
test("henry");
Console.Read();
}
}
}
當你熟了某些指令的時候,事情就變得簡單並不是想象中複雜.