使用直接二维GdiInteropRenderTarget的GDI对象泄漏

使用直接二维GdiInteropRenderTarget的GDI对象泄漏,interop,gdi,memory-leaks,direct2d,Interop,Gdi,Memory Leaks,Direct2d,我正在尝试在兼容的渲染目标上同时使用Gdi和Direct 2D渲染位图。 我使用D2D1_compatible_RENDER_target_OPTIONS_GDI_compatible选项创建兼容目标,然后执行以下操作: HDC hdc=NULL; ID2D1GdiInteropRenderTarget *gdiTarget=NULL; target->QueryInterface(__uuidof(ID2D1GdiInteropRenderTarget), (void**)&gd

我正在尝试在兼容的渲染目标上同时使用Gdi和Direct 2D渲染位图。 我使用D2D1_compatible_RENDER_target_OPTIONS_GDI_compatible选项创建兼容目标,然后执行以下操作:

HDC hdc=NULL;
ID2D1GdiInteropRenderTarget *gdiTarget=NULL;
target->QueryInterface(__uuidof(ID2D1GdiInteropRenderTarget), (void**)&gdiTarget);
target.BeginDraw();
HRESULT hr=gdiTarget->GetDC(D2D1_DC_INITIALIZE_MODE_CLEAR, &hdc);
if(SUCCEEDED(hr))
{
    /* Gdi drawing code(hdc)*/

gdiTarget->ReleaseDC(NULL);
}
/* Direct2D drawing code
target->EndDraw();
gdiTarget->Release();
但似乎有些地方出了问题,因为每次我调用这个渲染方法时,我都会得到许多GDI对象。我也尝试这样做:

HDC hdc=NULL;
ID2D1GdiInteropRenderTarget *gdiTarget=NULL;
target->QueryInterface(__uuidof(ID2D1GdiInteropRenderTarget), (void**)&gdiTarget);
target.BeginDraw();
HRESULT hr=gdiTarget->GetDC(D2D1_DC_INITIALIZE_MODE_CLEAR, &hdc);
if(SUCCEEDED(hr))
gdiTarget->ReleaseDC(NULL);
target->EndDraw();
gdiTarget->Release();
我也有泄密。 我还尝试在ID2D1GdiInteropRenderTarget创建的HDC上使用DeleteDC()或ReleaseDC(),但没有成功

有什么建议吗?
提前谢谢

如果渲染目标使用的是加速度,则结果的性能不会很好。您应该强烈考虑在D2D中自然地呈现。 原因是您要承担从GPU到系统的转移成本。我已经将许多绘图代码移植到本机D2D。有一些API可能需要GDI(xor等),但一般来说,即使是这些API也应该尝试另一种方法

我不确定为什么会出现泄漏,但您希望遵循以下指导原则:

我不建议使用dc渲染目标,这比使用GDI+要慢。 对于一些需要的调用,请使用第二种方法。
此外,您还需要处理可能在D2D中生效的任何剪辑/图层


最后,您需要在调用EndDraw之前释放GDI接口。

我发现了问题。它是一个未发布的d2dBitmap,有时会导致内存泄漏,当我试图发布ID2D1GdiInteropRenderTarget时,它导致Gdi对象泄漏

HDC hdc=NULL;
ID2D1GdiInteropRenderTarget *gdiTarget=NULL;
compatibleTarget->QueryInterface(__uuidof(ID2D1GdiInteropRenderTarget),(void**)&gdiTarget);
compatibleTarget.BeginDraw();
HRESULT hr=gdiTarget->GetDC(D2D1_DC_INITIALIZE_MODE_CLEAR, &hdc);
if(SUCCEEDED(hr))
{
    /* Gdi drawing code(hdc)*/

gdiTarget->ReleaseDC(NULL);
}
/* Direct2D drawing code
compatibleTarget->EndDraw();
gdiTarget->Release();
ID2D1Bitmap *bitmap=NULL;
compatibleTarget->GetBitmap(&bitmap);
target->BeginDraw();
target->DrawBitmap(bitmap);
target->EndDraw();
compatibleTarget->Release();    // I thought this only enough
bitmap->Release();              // This solved the problem
我仍然有点困惑于哪种类型的目标更适合使用(DC或Hwnd),因为我发现不同的性能取决于我是否使用Gpu。 特别是,我发现了以下问题:

  • 如果我使用DCRenderTarget,我就不能使用硬件加速(或默认设置),因为我一直在侵犯内存的受保护区域。如果使用HwnRenderTarget,则不会发生这种情况
  • 如果我使用HwndRenderTarget,一般来说一切都很好,但我失去了对窗口的关注,窗口无法识别按键信息,如果我使用Gpu,性能会下降很多,并强烈依赖于活动目标的数量(如果我使用软件加速,则不会发生这种情况)
有人遇到过同样的问题吗? 你能推荐一下吗