如何调试动态生成的方法



我有一个动态创建的程序集、一个模块、一个类和一个动态生成的方法。

AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(...);
ModuleBuilder module = assembly.DefineDynamicModule(...);
TypeBuilder tb = module.DefineType(...);
MethodBuilder mb = tb.DefineMethod(...);
ILGenerator gen = mb.GetILGenerator();

如何调试用ILGenerator生成的方法代码?我使用Visual Studio 2012调试器,但它只是逐步完成一个方法调用。

您需要将生成的代码标记为可调试代码
类似于:

Type daType = typeof(DebuggableAttribute);
ConstructorInfo ctorInfo = daType.GetConstructor(new Type[] { typeof(DebuggableAttribute.DebuggingModes) });
CustomAttributeBuilder caBuilder = new CustomAttributeBuilder(ctorInfo, new object[] { 
  DebuggableAttribute.DebuggingModes.DisableOptimizations | 
  DebuggableAttribute.DebuggingModes.Default
});
assembly.SetCustomAttribute(caBuilder);

您还应该添加一个源文件:

ISymbolDocumentWriter doc = module.DefineDocument(@"SourceCode.txt", Guid.Empty, Guid.Empty, Guid.Empty);

您现在应该能够进入动态生成的方法了。

如果您在没有任何源的情况下生成原始IL,那么:这总是很困难的。您可能需要考虑像Sigil这样的包,它是ILGenerator的包装器,但如果您犯了任何细微的错误(堆栈损坏等),它将为您提供有用的错误消息(在发出时,而不是在运行时)。

或者:在启用"保存到磁盘"的情况下写入模块,并在调试期间将常规dll写入磁盘-然后可以在dll上运行PEVerify,它会发现最典型的错误(同样是堆栈损坏等)。当然,你也可以将它加载到你最喜欢的IL工具中。

最新更新