You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++ DLL中Direct2D Clear函数触发AccessViolationException问题

Direct2D DLL调用Clear时触发AccessViolationException问题

在C编写的DLL中完成Direct2D初始化后,通过C# PInvoke调用Direct2D_Clear()函数时抛出AccessViolationException(提示尝试访问受保护内存),但直接在C环境中运行相同初始化逻辑的绘制循环无异常。DLL与C#程序均采用x64编译。

C++ DLL代码

初始化与Clear函数实现

DLL_EXPORT void Direct2D_Init(HWND _hwnd, UINT width, UINT height)
{
    D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pD2DFactory);

    // Create WIC factory
    HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, nullptr, CLSCTX_INPROC_SERVER,
        IID_IWICImagingFactory, reinterpret_cast<void**>(&g_pWICFactory));
    if (FAILED(hr))
    {
        // Handle error
        return;
    }

    // Create a render target
    D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties(
        D2D1_RENDER_TARGET_TYPE_DEFAULT, D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED));
    pD2DFactory->CreateHwndRenderTarget(props, D2D1::HwndRenderTargetProperties(_hwnd, D2D1::SizeU(width, height)), &pRenderTarget);
}

// 调用此函数时抛出异常:
DLL_EXPORT void Direct2D_Clear()
{
    pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::White));
}

C++本地无异常测试代码

// 使用上述相同的初始化方法
Direct2D_Init(hWnd, 800, 600);
while (true)
{
    pRenderTarget->BeginDraw();
    pRenderTarget->Clear(D2D1::ColorF(D2D1::ColorF::CornflowerBlue));
    pRenderTarget->EndDraw();
}

C# PInvoke调用代码

[DllImport(".\d2dlib.dll")]
static extern void Direct2D_Clear();
        
public void Begin()
{
    if (renderOption == RenderOption.Direct2D)
    { 
        Direct2D_Clear(); // System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
    }
    else
        ...
}         

补充说明:目前怀疑问题出在DLL编写方式或PInvoke调用环节。

内容的提问来源于stack exchange,提问作者DaFuze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 14:41:04