当满足某些条件时,我需要从我的 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/