c# - 非托管代码中 System.Diagnostics.Debugger.Launch() 的等效项是什么?

标签 c# c++ debugging

当满足某些条件时,我需要从我的 native C++ 程序启动调试器。在 C# 中,我只调用 System.Diagnostics.Debugger.Launch()。我认为 Win32 DebugBreak() 调用会执行我想要的操作,但如果没有调试器,它只会终止应用程序。

如何从 native 代码启动调试器的新实例(著名的“可能的调试器”对话框)?有可能吗?我可以尝试使用 COM 创建一个新的 Visual Studio 实例,但这有点复杂,而且还会将我锁定到特定版本的 VS。

最佳答案

我发现可以直接用当前进程的PID调用vsjitdebugger.exe。确保在 Tools->Options->Debugging->Just-in-Time in Visual Studio 中选择了“Native”。

这是启动调试器的 C++ 代码。它使用各种 Win32 API 的 UNICODE 版本。我得到系统目录,因为 CreateProcess() 不使用 PATH。

bool launchDebugger()
{
    // Get System directory, typically c:\windows\system32
    std::wstring systemDir(MAX_PATH+1, '\0');
    UINT nChars = GetSystemDirectoryW(&systemDir[0], systemDir.length());
    if (nChars == 0) return false; // failed to get system directory
    systemDir.resize(nChars);

    // Get process ID and create the command line
    DWORD pid = GetCurrentProcessId();
    std::wostringstream s;
    s << systemDir << L"\\vsjitdebugger.exe -p " << pid;
    std::wstring cmdLine = s.str();

    // Start debugger process
    STARTUPINFOW si;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    PROCESS_INFORMATION pi;
    ZeroMemory(&pi, sizeof(pi));

    if (!CreateProcessW(NULL, &cmdLine[0], NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) return false;

    // Close debugger process handles to eliminate resource leak
    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);

    // Wait for the debugger to attach
    while (!IsDebuggerPresent()) Sleep(100);

    // Stop execution so the debugger can take over
    DebugBreak();
    return true;
}

关于c# - 非托管代码中 System.Diagnostics.Debugger.Launch() 的等效项是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20337870/

相关文章:

c++ - Visual Studio C++ 组合框控件不适用于多字节字符集

c++ - 使用冒泡排序比较类对象

c# - WPF DataGrid SelectionChanged 事件取消单元格焦点问题

c# - 实现接口(interface)的 Blazor 组件列表

c# - 如果我在测试时在 System.Web.UI.Util 处遇到异常,如何对我的 HtmlHelper 扩展方法进行单元测试?

java - 我如何调试 Hadoop map reduce

debugging - 解决 'DevTools was disconnected from the page'和 Electron 助手死的技巧

c# - 如何更好地组合从一个接口(interface)继承的不同类型的通用列表?

Android NDK工具链异常处理seg faults

c++ - 可以在 gdb 中调用内联函数和/或使用 GCC 发出它们吗?