在Windows下如何在程序中获得当前调用栈信息

简介: Windows所提供的获取当前调用栈机制和Solaris有点类似,附件代码把它加以封装,以CallStack类提供给使用者。#ifndef _CALLSTACK_H_ #define _CALLSTACK_H_ #include list> #def...
Windows所提供的获取当前调用栈机制和Solaris有点类似,附件代码把它加以封装,以CallStack类提供给
使用者。
  1. #ifndef _CALLSTACK_H_
  2. #define _CALLSTACK_H_

  3. #include list>

  4. #define MAX_CALLSTACK_FRAMES 102400

  5. class CallStack
  6. {
  7. public:
  8.     static bool LoadDbgHelpLib (); //加载所使用的库dbghelp.dll,必须在初始化是调用。
  9.     int GetCallStack(); //获得当前调用栈所有指令地址PC
  10.    
  11.     //把在GetCallStack函数中所获得的所有指令地址转换成函数名和文件名、行号等信息,并打印出来
  12.     int GenCallStackDetails();

  13. private:
  14.     static char *BuildSymbolSearchpath();
  15.     static HANDLE m_process;
  16.     HANDLE m_thread;
  17.     std::listDWORD64> m_framePC;
  18. };
  19. #endif


使用示例:
  1. #include "CallStack.h"
  2. int main(int argc, char *argv[])
  3. {
  4.     if(!CallStack::LoadDbgHelpLi())
  5.     {
  6.          printf("Load dbghelp.dll failed!\n");
  7.          return -1;
  8.     }
  9.     CallStack *pStack = new CallStack();
  10.     pStack->GetCallStack();
  11.     pStack->GenCallStackDetails();
  12.     delete pStack;
  13.     return 0;
  14. }

  15. 结果是:
  16.  Call Stack:
  17.    f:\vs70builds\3077\vc\crtbld\crt\src\dbgdel.cpp (54): operator delete
  18.    f:\vs70builds\3077\vc\crtbld\crt\src\delete2.cpp (21): operator delete[]
  19.    e:\mydocuments\visual studio projects\allochook\allochook.cpp (46): main
  20.    f:\vs70builds\3077\vc\crtbld\crt\src\crt0.c (259): mainCRTStartup

注意:在Visiual Project下的工程一定要用debug模式编译。
详细请参照:
http://www.codeproject.com/Articles/9815/Visual-Leak-Detector-Enhanced-Memory-Leak-Detectio
zip.gif callstack.zip  
在Linux下如何在程序中获得当前调用栈信息
在Solaris下如何在程序中获得当前调用栈信息
在AIX下如何在程序中获得当前调用栈信息
《返璞归真--UNIX技术内幕》

目录
相关文章
|
9天前
|
消息中间件 编译器 API
Windows窗口程序
Windows窗口程序
|
29天前
|
Windows
实现Windows程序的数据更新
实现Windows程序的数据更新
12 0
|
29天前
|
Windows
构建布局良好的Windows程序
构建布局良好的Windows程序
11 0
|
29天前
|
C# Windows
初识Windows程序
初识Windows程序
10 0
|
2月前
|
Java Linux Windows
windows实现自动部署jar包运行程序
windows实现自动部署jar包运行程序
39 0
|
4月前
|
移动开发
【实用】一组原创原生样式的基础控件、UI组件样式(偏向移动端H5页面的样式)
【实用】一组原创原生样式的基础控件、UI组件样式(偏向移动端H5页面的样式)
【实用】一组原创原生样式的基础控件、UI组件样式(偏向移动端H5页面的样式)
|
3月前
|
API Python Windows
python3应用windows api对后台程序窗口及桌面截图并保存的方法
python3应用windows api对后台程序窗口及桌面截图并保存的方法
89 1
|
2月前
|
Windows
火山中文编程 -- 第一个windows程序
火山中文编程 -- 第一个windows程序
12 0
|
6月前
|
C++ Windows
winform 程序打包成windows安装包
winform 程序打包成windows安装包前提:VS2019,winform 程序已经有一个完整可运行的 winform 程序。VS中上方扩展选项卡,选择 管理扩展,在打开的弹窗中选择联机,在右侧搜索框搜索 installer, 在中间显示的结果选择 Microsoft Visual Studio Installer Projects 点击下载。下载完成之后,关闭vs,自动打开扩展的安...
50 0
winform 程序打包成windows安装包
|
6月前
|
Java Linux Windows
【Java用法】Java在Linux下获取当前程序路径以及在Windows下获取当前路径对比
【Java用法】Java在Linux下获取当前程序路径以及在Windows下获取当前路径对比
134 0