释放 COM 对象 (WICImagingFactory) 时出现段错误

问题描述 投票:0回答:1

我已经开始使用 Direct2D 创建一个简单的游戏引擎,但每当我发布 IWICImagingFactory* 时,我都遇到了段错误的问题。仅当程序关闭时才会出现此问题。

最小可重复样品:

#include <Windows.h>
#include <d2d1.h>
#include <wincodec.h>

template <class Interface>
void SafeRelease(
    Interface *&pInterfaceToRelease)
{
    if (pInterfaceToRelease != nullptr)
    {
        pInterfaceToRelease->Release();
        pInterfaceToRelease = nullptr;
    }
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }

    return DefWindowProc(hWnd, uMsg, wParam, lParam);
}

int WINAPI wWinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPWSTR pCmdLine, int nCmdShow)
{
    // Register Window Class
    WNDCLASS wc = {};
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInst;
    wc.lpszClassName = L"Class Name";
    RegisterClass(&wc);

    // Create and Show Window
    HWND hWnd = CreateWindowEx(0, L"Class Name", L"Test Window", WS_OVERLAPPEDWINDOW,
                               CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                               NULL, NULL, hInst, NULL);
    ShowWindow(hWnd, nCmdShow);

    // Create d2d factory and render target
    ID2D1Factory *pD2DFactory;
    ID2D1HwndRenderTarget *pRT;
    D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pD2DFactory);
    RECT rc;
    GetClientRect(hWnd, &rc);
    pD2DFactory->CreateHwndRenderTarget(
        D2D1::RenderTargetProperties(),
        D2D1::HwndRenderTargetProperties(hWnd, D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top)),
        &pRT);

    // Create Imaging Factory
    IWICImagingFactory *pWICFactory;
    CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pWICFactory));

    // Start loop
    bool windowOpen = true;
    MSG msg;
    while (windowOpen)
    {
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        if (msg.message == WM_QUIT)
        {
            SafeRelease(pWICFactory);
            SafeRelease(pRT);
            SafeRelease(pD2DFactory);
            UnregisterClass(L"Class Name", hInst);
            CoUninitialize();
            windowOpen = false;
            break;
        }

        pRT->BeginDraw();
        pRT->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
        pRT->EndDraw();
    }

    return 0;
}

我正在使用 gcc 编译程序:

g++ -fdiagnostics-color=always -g test.cpp -municode -mwindows -ld2d1 -lole32 -lwindowscodecs -o test.exe

除了通过不加载任何图像来创建 IWICImagingFactory* 之外,我还尝试消除对 IWICImagingFactory* 的任何使用,但问题仍然存在。图像仍然可以正常加载。我还确保在调用 Release() 之前指针不为空。

c++ com directx direct2d
1个回答
0
投票

感谢所有回复的人。我提供的代码示例的问题是它没有调用

CoInitialize()
,我忘了包含它。我的程序本身的问题是有一个对象持有一个
ID2D1Bitmap*
,它是用
IWICImagingFactory
创建的并存储在静态内存中。问题是位图在
IWICImagingFactory
之后被释放,这导致了段错误。

© www.soinside.com 2019 - 2024. All rights reserved.