输入布局、访问冲突、错误处理无法像我希望的那样工作

Input layout, access violation, error handling not working like i want it to

我正在学习 DirectX 11,我想深入了解 DirectX 调试,因为我在第 199 行(创建 inputLayout)遇到访问冲突读取位置错误 我试图得到一个显示 directX 错误的错误框,因为我在某处读到,让该框显示有关错误的信息是一个很好的编程习惯 有任何想法吗? 另外,如果能帮助输入布局,我们将不胜感激

ID3DBlob *VS, *PS;

#if defined(DEBUG) | defined(_DEBUG)
#ifndef HR
#define HR(x) \
{ \
HRESULT hr = (x); \
if(FAILED(hr)) \
{ \
DXTrace(__FILE__, (DWORD)__LINE__, hr, L#x, true); \
} \
}
#endif
#else
#ifndef HR
#define HR(x) (x)
#endif
#endif

D3DX11CompileFromFile(L"shaders.fx", 0, 0, "VS", "vs_5_0", 0, 0, 0, &VS, 0, 0);
D3DX11CompileFromFile(L"shaders.fx", 0, 0, "PS", "ps_5_0", 0, 0, 0, &PS, 0, 0);

device->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &vShader);
device->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pShader);

VS->Release();
PS->Release();
context->VSSetShader(vShader, 0, 0);
context->PSSetShader(pShader, 0, 0);


// define the input layout
D3D11_INPUT_ELEMENT_DESC layout[] =
  {
    { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};


UINT numElements = ARRAYSIZE(layout);

//below gives me access violation error and says that &inputLayout is NULL 
HR(device->CreateInputLayout(layout, numElements, VS->GetBufferPointer(), VS->GetBufferSize(), &inputLayout));

您在根据上述代码创建布局之前正在释放 VS blob。在创建输入布局时需要原始的顶点着色器二进制 blob,以便 Direct3D 可以验证它们是否匹配。

一个简单的解决方法是将 VS->Release(); 移动到调用 CreateInputLayout 之后。

更好的答案是删除对 Release 的所有显式使用,而是依赖像 Microsoft::WRL::ComPtr.

这样的智能指针
#include <wrl/client.h>

using Microsoft::WRL::ComPtr;

...

ComPtr<ID3DBlob> VS, PS;

...

D3DX11CompileFromFile(L"shaders.fx", 0, 0, "VS", "vs_5_0", 0, 0, 0, &VS, 0, 0);
D3DX11CompileFromFile(L"shaders.fx", 0, 0, "PS", "ps_5_0", 0, 0, 0, &PS, 0, 0);

device->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &vShader);
device->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pShader);

context->VSSetShader(vShader, 0, 0);
context->PSSetShader(pShader, 0, 0);

...

//below gives me access violation error and says that &inputLayout is NULL 
HR(device->CreateInputLayout(layout, numElements, VS->GetBufferPointer(), VS->GetBufferSize()));

每当 VSPS 超出范围时,它们将自行清除。