How can I programmatically examine the stack in my Visual Studio extension?

随声附和 提交于 2020-08-11 18:42:13

问题


In a VS extension, assume that the code has just hit a breakpoint, and is in break mode. How can I programmatically examine the stack? Also, is there a way to figure out what the last executed statement was?

I haven't been able to find an advanced sample. There are hello-world type samples but they are mostly focused on adding/modifying UI elements in Visual Studio IDE.


回答1:


You'll need to hook into the EnvDTE.Events.DebuggerEvents.OnEnterBreakMode event or equivalent to know when the process stops (and thus has a callstack). Be careful to keep a reference to EnvDTE.Events.DebuggerEvents otherwise it can be garbage collected and the connection to your event handler lost (normally this can't happen in C# but because of the way the EnvDTE event COM wrappers are implemented this is a known issue).

Once the debugger is in break mode, you can iterate EnvDte.Debugger.CurrentThread.StackFrames like so:

foreach (var frame in dte.Debugger.CurrentThread.StackFrames.Cast<EnvDTE.StackFrame>())
    ...

If you wish to modify the current thread/stack or get more details than EnvDTE exposes, this is also possible but non-trivial. There is a COM interface called IDebuggerInternal that exposes these things directly, but it's not exported from the public MS DLLs. However, since it's a COM interface, you can re-declare it in C# and cast the SVsShellDebugger instance to it. If you want to go down this route I suggest disassembling Microsoft.VisualStudio.Debugger.Interop.Internal, Version=11.0.0.0 (e.g. with dotPeek) to get the interface definition and GUID.



来源:https://stackoverflow.com/questions/62555122/how-can-i-programmatically-examine-the-stack-in-my-visual-studio-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!