Damon Swayn
Damon Swayn

Reputation: 1344

D3DX11CompileFromFile returns S_OK but CreateVertexShader throws error

So I have the following code:

    extern ID3D11Device* dev;
    extern ID3D11DeviceContext* devcon;        

    //shaders
    ID3D10Blob *VS, *PS, *error;
    HRESULT r;
    error = 0;

    r = D3DX11CompileFromFile(L"shaders.hlsl", 0, 0, "VShader", "vs_5_0", D3DCOMPILE_DEBUG, 0, 0, &VS, &error, 0);
    if(FAILED(r))
    {
        LPCWSTR errmsg = (LPCWSTR)error->GetBufferPointer();
        MessageBox(hWnd, errmsg, L"error", MB_OK);
        return;
    }

    error = 0;
    r = D3DX11CompileFromFile(L"shaders.hlsl", 0, 0, "PShader", "ps_5_0", D3DCOMPILE_DEBUG, 0, 0, &PS, &error, 0);
    if(FAILED(r))
    {
        LPCWSTR errmsg = (LPCWSTR)error->GetBufferPointer();
        MessageBox(hWnd, errmsg, L"error", MB_OK);
        return;
    }

    // encapsulate both shaders into shader objects
    r = dev->CreateVertexShader(VS->GetBufferPointer(), VS->GetBufferSize(), NULL, &vertexShader);
    r = dev->CreatePixelShader(PS->GetBufferPointer(), PS->GetBufferSize(), NULL, &pixelShader);

    devcon->VSSetShader(this->vertexShader, 0, 0);
    devcon->PSSetShader(this->pixelShader, 0, 0);

Running the code, D3DX11CompileFromFile for both vertex and pixel shaders returns S_OK, however when the code hits CreateVertexShader() it throws an access violation, and for the life of me I can't figure out why. I've probably done something rather stupid, I just can't seem to figure it out.

Upvotes: 0

Views: 1908

Answers (2)

Alex
Alex

Reputation: 1924

Most common reasons for that kind of error are either dev or VS is null/uninitialized. If the access violation is occurring at 0x00000xxx, then it's a null pointer. If it's 0xCCCCCxxx, then it's an uninitialized pointer (assuming you're running under Visual Studio). Also, it is good practice to zero out interface pointers (such as VS and PS in your code) before they're allocated and after they're freed (and the pointer is about to go out of scope), as this prevents a double free on the pointer and prevents the pointer from not tripping a breakpoint set to stop when the pointer is either not allocated correctly or is somehow overwritten.

Upvotes: 1

Jader J Rivera
Jader J Rivera

Reputation: 409

Well I'm no pro in DirectX but if I'm correct a c++ compiler will turn a .hlsl into a .cso while it's running. Therefore you should change the D3DX11CompileFromFile parameter from L"shaders.hlsl" to L"shaders.cso" and do the same with the other call to the function.

This should allow the program to correctly read the .hlsl files.

Upvotes: 0

Related Questions