IL基础示例
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Reflection; 5 using System.Reflection.Emit; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace ConsoleApp1 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 //定义一个程序集 16 var assemblyName = new AssemblyName("Holle"); 17 //在程序域中定义/获取当前定义的程序集 18 var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); 19 //保存持久动态模块 20 var moduleBuileder = assemblyBuilder.DefineDynamicModule("HolleModule", "Holle.exe"); 21 //定义类 22 var typeBuilder = moduleBuileder.DefineType("HelloHolleClass", TypeAttributes.Public); 23 //给定义的类添加方法 24 //var methodBuilder = typeBuilder.DefineMethod("SayHelloMethod", MethodAttributes.Public | MethodAttributes.Static, null, null); 25 26 var showMethod = typeBuilder.DefineMethod("Show", MethodAttributes.Public | MethodAttributes.Static, null, null); 27 28 ////在类中定义变量 29 //FieldBuilder fieldName = typeBuilder.DefineField("Name", typeof(string), FieldAttributes.Private | FieldAttributes.Static); 30 31 //将自定义的动态程序集转换成IL 32 ILGenerator ilOfShow = showMethod.GetILGenerator(); 33 //定义show方法 34 //定义变量 35 LocalBuilder localName = ilOfShow.DeclareLocal(typeof(string)); 36 LocalBuilder local2Name = ilOfShow.DeclareLocal(typeof(string)); 37 38 //补码 39 ilOfShow.Emit(OpCodes.Nop); 40 //调用对应类的方法 41 ilOfShow.Emit(OpCodes.Call, typeof(Console).GetMethod("ReadLine")); 42 //赋值 43 ilOfShow.Emit(OpCodes.Stloc, localName); 44 45 //声明字串 46 ilOfShow.Emit(OpCodes.Ldstr, "姓名:{1} 年龄:{0}"); 47 48 //声明数值 49 ilOfShow.Emit(OpCodes.Ldc_I4, 18); 50 //装箱,转类型 51 ilOfShow.Emit(OpCodes.Box,typeof(int)); 52 53 //ilOfShow.Emit(OpCodes.Ldstr,"ni"); 54 55 //将变量重新加载 56 ilOfShow.Emit(OpCodes.Ldloc, localName); 57 //调用替代方法 58 ilOfShow.Emit(OpCodes.Call, typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object), typeof(object) })); 59 //赋值? 60 ilOfShow.Emit(OpCodes.Stloc, local2Name); 61 62 //结束方法 63 ilOfShow.Emit(OpCodes.Ret); 64 65 66 //创建实例 67 var helloHolleClassType = typeBuilder.CreateType(); 68 //设置程序入口的方法 69 assemblyBuilder.SetEntryPoint(helloHolleClassType.GetMethod("Show")); 70 //保存应用 71 assemblyBuilder.Save("Holle.exe"); 72 73 74 } 75 } 76 }
转换成C#
1 using System; 2 3 // Token: 0x02000002 RID: 2 4 public class HelloHolleClass 5 { 6 // Token: 0x06000001 RID: 1 RVA: 0x00002050 File Offset: 0x00000250 7 public static void Show() 8 { 9 string arg = Console.ReadLine(); 10 string text = string.Format("姓名:{1} 年龄:{0}", 18, arg); 11 } 12 }
对于局部变量名自定义稍后更新