microsoft / CsWin32

A source generator to add a user-defined set of Win32 P/Invoke methods and supporting types to a C# project.
MIT License
1.99k stars 84 forks source link

Access violation writing location when calling DirectX APIs. #1134

Closed Dotpys closed 4 months ago

Dotpys commented 5 months ago

I'm rewriting my DirectX rust project in C# and this piece of code (same logic of the rust project) throws an Acces Violation exception.

Actual behavior

var descriptorHeapDescription = new D3D12_DESCRIPTOR_HEAP_DESC()
{
    NumDescriptors = 3,
    Type = D3D12_DESCRIPTOR_HEAP_TYPE.D3D12_DESCRIPTOR_HEAP_TYPE_RTV
};
// Device is an object that implements ID3D12Device10.
Device.CreateDescriptorHeap(descriptorHeapDescription, typeof(ID3D12DescriptorHeap).GUID, out object descriptorHeap);

((ID3D12DescriptorHeap)descriptorHeap).GetCPUDescriptorHandleForHeapStart();

That last line where i call the .GetCPUDescriptorHandleForHeapStart() is where this exception is thrown:

Exception thrown at 0x00007FFB01900657 (D3D12Core.dll) in DirectXPInvoke.exe: 0xC0000005: Access violation writing location 0x0000000000000009.

Expected behavior

As this doesn't happen on rust and I'm basically translating from one language to another I expect this to work normally and return the handle. I also put ID3D12Device10.CreateDescriptorHeap inside the preserveSigMethods of NativeMethods.json, and checked if the HRESULT of the Heap Creation was successful returning S_OK. It did create succesfully the heap.

Repro steps

  1. NativeMethods.txt content:
    
    Windows.Win32.Foundation
    Windows.Win32.System.LibraryLoader.GetModuleHandleW
    Windows.Win32.UI.WindowsAndMessaging

//=====DirectX Stuff===== D3D12GetDebugInterface D3D12CreateDevice

ID3D12CommandQueue ID3D12Debug ID3D12DescriptorHeap ID3D12Device ID3D12Device10 ID3D12Resource2

D3D_FEATURE_LEVEL

//=====DXGI Stuff===== CreateDXGIFactory2

IDXGIAdapter4 IDXGIFactory7 IDXGISwapChain4

DXGI_ADAPTER_FLAG DXGI_CREATE_FACTORY_DEBUG DXGI_MWA_NO_ALT_ENTER


2. `NativeMethods.json`
```json
{
  "$schema": "https://aka.ms/CsWin32.schema.json",
  "comInterop": {
    "preserveSigMethods": [
      "ID3D12Device10.CreateDescriptorHeap"
    ]
  }
}

Context

JeremyKuhne commented 4 months ago

Dupe of #167. I've added some more comments there. Hopefully we can address this now on .NET 6+.