Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 如何调试动态生成的方法?_.net_Debugging_Dynamic_Visual Studio 2012_Il - Fatal编程技术网

.net 如何调试动态生成的方法?

.net 如何调试动态生成的方法?,.net,debugging,dynamic,visual-studio-2012,il,.net,Debugging,Dynamic,Visual Studio 2012,Il,我有一个动态创建的程序集、一个模块、一个类和一个动态生成的方法 AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(...); ModuleBuilder module = assembly.DefineDynamicModule(...); TypeBuilder tb = module.DefineType(...); MethodBuilder mb = tb.DefineMethod(...);

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

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,那么:这总是很粗糙的。您可能需要考虑一个类似于“包”的包装,它是围绕<代码> ILGenerator < /C> >,但它会给您<强>有用的错误消息(在发射时,而不是在运行时),如果您犯了任何微妙的错误-堆栈损坏等,


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

我在执行
ISymbolDocumentWriter doc=module.DefineDocument(@“SourceCode.txt”、Guid.Empty、Guid.Empty、Guid.Empty)时捕获了一个异常InvalidOperationException:不是调试模块生成器。定义模块时,需要告诉它发出符号信息。使用构造函数并将第二个参数设置为
true
。实际上有一个很好的例子。