我编写了一些函数来使用ILGenerator创建一个exe文件。我想要的是向用户展示在没有使用外部工具(如ILDasm或Reflector )的情况下生成的IL语言。
在我的程序执行期间,我将每个OpCode添加到ILGenerator中,因此我可以使用带有OpCode表示的字符串将每个OpCode保存在列表中,但我希望直接获得IL代码。能办到吗?
:我正在使用Mono2.6。
发布于 2012-02-23 09:12:04
正如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 );
}
}当然,它可以做得更有效,但它解决了我的问题。
发布于 2012-02-22 13:12:56
如果您有一个MethodBuilder,您应该能够使用builder.GetMethodBody().GetILAsByteArray()作为一个byte[]来获取IL。但是,要理解这一点,您需要以某种方式解析它。
因此,更好的选择可能是使用赛西尔,它可以以可读的格式提供程序集的IL代码。
https://stackoverflow.com/questions/9393764
复制相似问题