Windows c++ 打印堆栈信息
时间: 2024-10-06 11:02:02 浏览: 112
在Windows C++中打印堆栈信息,通常是为了调试程序时查看当前调用堆栈,以便追踪错误来源。这可以通过第三方库如DbgHelp.dll或者一些系统API函数来实现。以下是使用`_asm`指令和`MiniDumpWriteDump`函数的一个简单示例:
```cpp
#include <windows.h>
#include <dbghelp.h>
void PrintStackTrace()
{
HANDLE hProcess = GetCurrentProcess();
void *stackBuffer[4096];
ULONG64 stackSize;
MINIDUMP_EXCEPTION_INFORMATION exInfo;
ZeroMemory(&exInfo, sizeof(exInfo));
exInfo.ThreadId = GetCurrentThreadId();
if (SymInitialize(hProcess, NULL, TRUE) !=SYMBOL_SUCCESS)
return; // 初始化符号表失败
if (!MiniDumpWriteDump(hProcess, GetCurrentProcessId(), NULL, MiniDumpWithFullMemory | MiniDumpExceptionInformation,
stackBuffer, sizeof(stackBuffer), &exInfo))
{
OutputDebugString("Failed to write minidump.\n");
return; // 写入堆栈dump失败
}
CONTEXT context;
RtlCaptureContext(&context);
_asm {
mov eax, [esp] // 获取栈顶地址
mov edi, stackBuffer // 将地址复制到缓冲区
rep movsd // 复制整个堆栈到缓冲区
}
for (size_t i = 0; i < sizeof(stackBuffer); i += sizeof(void*))
{
printf("Stack Frame at %p:\n", (void*)stackBuffer[i]);
DWORD symbol = SymFromAddr(hProcess, (DWORD64)stackBuffer[i], NULL);
printf("\tFunction: %s\n", !symbol ? "(unknown)" : SymGetModuleFileName(SymGetModuleBase(symbol), NULL, 0));
}
}
阅读全文