如何在msvc++中获得相当c#风格的堆栈跟踪?
How do you get a fairly C#-esque stack trace in MSVC++?
在c#中,您可以获得以下类型的堆栈跟踪:
at ExceptionGenerator.Program.three() in c:UsersADIMADocumentsVisual Stud
io 2013ProjectsExceptionGeneratorExceptionGeneratorProgram.cs:line 36
at ExceptionGenerator.Program.two() in c:UsersADIMADocumentsVisual Studio
2013ProjectsExceptionGeneratorExceptionGeneratorProgram.cs:line 31
at ExceptionGenerator.Program.one() in c:UsersADIMADocumentsVisual Studio
2013ProjectsExceptionGeneratorExceptionGeneratorProgram.cs:line 26
at ExceptionGenerator.Program.Main(String[] args) in c:UsersADIMADocuments
Visual Studio 2013ProjectsExceptionGeneratorExceptionGeneratorProgram.cs:li
ne 15
我想在c++中做同样的事情,但我不确定两件事…如何获得文件以及所处的行号?
示例代码我已经工作到目前为止:
// StackTracing.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <process.h>
#include <iostream>
#include <Windows.h>
#include "dbghelp.h"
using namespace std;
int LogStackTrace()
{
void *stack[100];
WORD numberOfFrames;
SYMBOL_INFO *symbol;
HANDLE process;
process = GetCurrentProcess();
SymInitialize(process, NULL, TRUE);
numberOfFrames = CaptureStackBackTrace(0, 1000, stack, NULL);
symbol = (SYMBOL_INFO *)calloc(sizeof(SYMBOL_INFO)+256 * sizeof(char), 1);
symbol->MaxNameLen = 255;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
printf("Caught exception ");
for (int i = 0; i < numberOfFrames; i++)
{
SymFromAddr(process, (DWORD64)(stack[i]), 0, symbol);
printf("at %s, address 0x%0Xn", symbol->Name, symbol->Address);
}
return 0;
}
void function2()
{
throw new exception("Expected exception.");
}
void function1()
{
function2();
}
void function0()
{
function1();
}
static void threadFunction(void *param)
{
try
{
function0();
}
catch (...)
{
LogStackTrace();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
try
{
_beginthread(threadFunction, 0, NULL);
}
catch (...)
{
LogStackTrace();
}
printf("Press any key to exit.n");
cin.get();
return 0;
}
输出:Press any key to exit.
Caught exception at LogStackTrace, address 0xB13860
at threadFunction, address 0xB15680
at beginthread, address 0xFCF31E0
at endthread, address 0xFCF33E0
at BaseThreadInitThunk, address 0x7656494F
at RtlInitializeExceptionChain, address 0x772E986A
at RtlInitializeExceptionChain, address 0x772E986A
也许堆栈框架类在这里可以帮到你。
相关文章:
- Qt VTK交互风格的信号到小部件
- 我可以使用条件运算符初始化C风格的字符串文字吗
- Visual Studio 2019:插入多个C++风格的单行注释
- 如何在本地机器上运行c++和javascript客户端代码(hackerbank风格)
- 算法问题:查找从堆栈中弹出的所有序列
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- Visual Studio(或任何其他工具)能否将地址解释为调用堆栈(boost上下文)的开头
- 为什么调用堆栈数组会导致内存泄漏
- gdb错误:Backtrace已停止:上一帧与此帧相同(堆栈已损坏?)
- 在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误
- 我的 int main() 中出现堆栈溢出错误
- 堆栈和队列是否像C++中的数组一样传递?
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 从堆栈分配的原始指针构造智能指针
- 在函数范围内在堆栈上分配的数组在离开函数时是否总是被释放?
- 堆栈中大小变量输入错误 (C++)
- 野牛风格:使用我自己的堆栈不好吗?全球都很糟糕
- 在 C/C++ 中使用堆栈进行内存管理时的编码风格
- 如何在msvc++中获得相当c#风格的堆栈跟踪?