1

我正在编写一个包装类来在 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 函数,即使我不调用 _CrtDumpMemoryLeaks(),MFC 应用程序也会检测到内存泄漏并显示在输出窗口中,因为我认为调试中的 MFC 可能在内部调用此函数,但它不适用于WPF 测试应用程序。

4

1 回答 1

0

得到它的工作。以下链接供参考

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

于 2011-06-02T17:43:46.807 回答