簡體   English   中英

如何在MSVC ++中獲得相當C#風格的堆棧跟蹤?

[英]How do you get a fairly C#-esque stack trace in MSVC++?

在C#中,您將獲得以下類型的堆棧跟蹤:

   at ExceptionGenerator.Program.three() in c:\Users\ADIMA\Documents\Visual Stud
io 2013\Projects\ExceptionGenerator\ExceptionGenerator\Program.cs:line 36
   at ExceptionGenerator.Program.two() in c:\Users\ADIMA\Documents\Visual Studio
 2013\Projects\ExceptionGenerator\ExceptionGenerator\Program.cs:line 31
   at ExceptionGenerator.Program.one() in c:\Users\ADIMA\Documents\Visual Studio
 2013\Projects\ExceptionGenerator\ExceptionGenerator\Program.cs:line 26
   at ExceptionGenerator.Program.Main(String[] args) in c:\Users\ADIMA\Documents
\Visual Studio 2013\Projects\ExceptionGenerator\ExceptionGenerator\Program.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%0X\n", 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

也許堆棧框架類可以在這里為您提供幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM