C# 从ILGenerator检索代码
我写了一些函数来创建一个exe文件使用ILGenerator。我想向用户展示的是不使用ILDasm或Reflector等外部工具生成的IL语言 在我的程序执行期间,我已将每个操作码添加到ILGenerator,因此我可以使用带有操作码表示的字符串将每个操作码保存在列表中,但我更希望直接获取IL代码。能做到吗C# 从ILGenerator检索代码,c#,.net,mono,command-line-interface,ilgenerator,C#,.net,Mono,Command Line Interface,Ilgenerator,我写了一些函数来创建一个exe文件使用ILGenerator。我想向用户展示的是不使用ILDasm或Reflector等外部工具生成的IL语言 在我的程序执行期间,我已将每个操作码添加到ILGenerator,因此我可以使用带有操作码表示的字符串将每个操作码保存在列表中,但我更希望直接获取IL代码。能做到吗 重要:我正在使用Mono 2.6。如果您有MethodBuilder,您应该能够使用builder.GetMethodBody().GetILAsByteArray()将IL作为字节[]获取
重要:我正在使用Mono 2.6。如果您有
MethodBuilder
,您应该能够使用builder.GetMethodBody().GetILAsByteArray()
将IL作为字节[]
获取。但要想从中获得任何意义,您需要以某种方式解析它
因此,更好的选择可能是使用,它可以以可读的格式为您提供程序集的IL代码。正如Hans Passant和svick所说,答案是Mono.Cecil。让我们看看:
using Mono.Cecil;
using Mono.Cecil.Cil;
[...]
public void Print( ) {
AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly( this.module_name );
int i = 0, j = 0;
foreach ( TypeDefinition t in assembly.MainModule.Types ) {
if ( t.Name == "FooClass" ) {
j = i;
}
i++;
}
TypeDefinition type = assembly.MainModule.Types[ j ];
i = j = 0;
foreach ( MethodDefinition md in type.Methods ) {
if ( md.Name == "BarMethod" ) {
j = i;
}
i++;
}
MethodDefinition foundMethod = type.Methods[ j ];
foreach( Instruction instr in foundMethod.Body.Instructions ) {
System.Console.WriteLine( "{0} {1} {2}", instr.Offset, instr.OpCode, instr.Operand );
}
}
当然,它可以做得更有效,但它解决了我的问题。Mono.Cecil是这类问题的标准答案。我认为使用LINQ和
Single()
可以轻松地重写代码,使其可读性更高。