在托管代码C#/WPF中调用_CrtDumpMemoryLeaks()

本文关键字:CrtDumpMemoryLeaks 调用 托管代码 WPF | 更新日期: 2023-09-27 17:58:15

我正在编写一个包装类来调用WPF应用程序中的_CrtDumpMemoryLeaks()。我正在WPF应用程序中加载一个C语言DLL,并想看看DLL中是否存在任何内存泄漏,因为WPF也充当DLL的测试应用程序。

class MemLeak
{
    static int _CRTDBG_ALLOC_MEM_DF   =  0x01;
    static int _CRTDBG_LEAK_CHECK_DF  =  0x20;        
    static int _CRTDBG_MODE_DEBUG     =  0x2;
    static int _CRTDBG_MODE_WNDW      =  0x4;
    static int _CRT_WARN              =  0;
    static int _CRT_ERROR             =  1;
    static int _CRT_ASSERT            =  2;
    [DllImportAttribute("msvcrtd.dll", EntryPoint = "_CrtDumpMemoryLeaks", SetLastError = true)]
    static extern int _CrtDumpMemoryLeaks();
    [DllImportAttribute("msvcrtd.DLL", EntryPoint = "_CrtSetDbgFlag")]
    static extern int _CrtSetDbgFlag(int newFlag);
    [DllImportAttribute("msvcrtd.DLL", EntryPoint = "_CrtSetReportMode")]
    static extern int _CrtSetReportMode(int reportType, int reportMode);
    public static void StartMemLeakLogging()
    {
        _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
        _CrtSetReportMode(_CRT_ERROR | _CRT_WARN | _CRT_ASSERT, _CRTDBG_MODE_DEBUG);
    }
    public static void StopMemLeakLogging()
    {
        _CrtSetReportMode(_CRT_ERROR | _CRT_WARN | _CRT_ASSERT, _CRTDBG_MODE_DEBUG | _CRTDBG_MODE_WNDW);
        int i = _CrtDumpMemoryLeaks();
    }
}

我使用的是Windows XP Professional SP3上的Visual Studio 2008 SP1。奇怪的是,我不得不下载msvcrtd.dll文件,因为系统找不到它。之后,只需将它复制到调试文件夹中,应用程序就开始工作了。然而,在调试过程中,即使我有意分配内存而没有在DLL代码中释放,我也不会在输出窗口中看到内存泄漏信息。

此外,我无法更改DLL的源代码,否则我会尝试将这些函数放入DLL源代码中。我尝试创建一个MFC应用程序并调用DLL函数,MFC应用程序检测到内存泄漏并显示在输出窗口中,即使我不调用_CrtDumpMemoryLeaks(),因为我认为调试中的MFC可能在内部调用此函数,但它不适用于WPF测试应用程序。

在托管代码C#/WPF中调用_CrtDumpMemoryLeaks()

工作正常。以下链接供参考

http://social.msdn.microsoft.com/Forums/en/clr/thread/484de950-f488-452e-a9bf-b8b4cd2d1f75

相关文章:
  • 没有找到相关文章