smourier / DirectN

Direct interop Code for .NET Framework, .NET Core and .NET 5+ : DXGI, WIC, DirectX 9 to 12, Direct2D, Direct Write, Direct Composition, Media Foundation, WASAPI, CodecAPI, GDI, Spatial Audio, DVD, Windows Media Player, UWP DXInterop, WinUI3, etc.
MIT License
311 stars 28 forks source link

How to use DirectX11 with D3DImage #33

Closed ThusMad closed 1 year ago

ThusMad commented 1 year ago

Hi @smourier 👋 I'm using this sample to create my own control that I'll be using to draw some 2d stuff. Since the SharpDX is not supported for .Net 5.0+, I've rewritten the code in sample with DirectN. The code I ended with here but I faced a error image

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

What I'm missing? In what direction should I look? Maybe there is a good sample?

smourier commented 1 year ago

Hi,

Do you have a full reproducing sample (all files, project file, etc.) so it's easier for me to take a look?

ThusMad commented 1 year ago

Yes, here is a small project containing my code https://github.com/ThusMad/D3DDx11

smourier commented 1 year ago

This is not related to DirectN, the problem comes from how you use DirectX9's CreateTextureAPI.

As you can see from the doc here: https://learn.microsoft.com/en-us/windows/win32/api/d3d9helper/nf-d3d9helper-idirect3ddevice9-createtexture, this is the method's layout:

HRESULT CreateTexture(
  [in]          UINT              Width,
  [in]          UINT              Height,
  [in]          UINT              Levels,
  [in]          DWORD             Usage,
  [in]          D3DFORMAT         Format,
  [in]          D3DPOOL           Pool,
  [out, retval] IDirect3DTexture9 **ppTexture,
  [in]          HANDLE            *pSharedHandle
);

so, pSharedHandleis a pointer to a HANDLE, not a HANDLE.

To fix it you must allocate some memory and write the shared handle to it, or use DirectN's ComMemorytool which will handle that for you:

using var handlePtr = new ComMemory(handle);
var hr = _d3DDevice.Object.CreateTexture(description.Width, description.Height, 1, Constants.D3DUSAGE_RENDERTARGET,
    format, _D3DPOOL.D3DPOOL_DEFAULT, out var texture, handlePtr.Pointer);
ThusMad commented 1 year ago

Oh, i see, now it works, thx a lot.