Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

c++ - What does ComPtr.As() do?

I am working on learning DirectX 12 from some examples but I am having trouble understanding what does the ComPtr.As() method does.

ComPtr<ID3D12Device> device;
ComPtr<ID3D12Device> device2; 

// Do Stuff with Device
device.As(&device2); // What does this do?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Where did you find this example code? It looks fishy. This is kind of a nonsense use of As. It's equally silly if you expand it to the underlying QueryInterface:

hr = device->QueryInterface( IID_PPV_ARGS(device2) );

In fact, your code would be better written as:

device2 = device;

Typically you'd use As to obtain a new interface from an existing interface. For example with Direct3D 11, you create the device as a Direct3D 11.0 interface and then have to QueryInterface the 11.1, 11.2, 11.3, and/or 11.4 versions to use them:

ComPtr<ID3D11Device> device;
DX::ThrowIfFailed(D3D11CreateDevice(..., device.ReleaseAndGetAddressOf());

ComPtr<ID3D11Device2> device2;
hr = device.As(&device2);
if (FAILED(hr))
    // Do whatever handling you do if the system doesn't support 11.2

Another common use with Direct3D 11 is dealing with the debug interfaces which may not be present:

#ifndef NDEBUG
    ComPtr<ID3D11Debug> d3dDebug;
    if (SUCCEEDED(device.As(&d3dDebug)))
    {
        ComPtr<ID3D11InfoQueue> d3dInfoQueue;
        if (SUCCEEDED(d3dDebug.As(&d3dInfoQueue)))
        {
#ifdef _DEBUG
            d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, true);
            d3dInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, true);
#endif
            D3D11_MESSAGE_ID hide [] =
            {
                D3D11_MESSAGE_ID_SETPRIVATEDATA_CHANGINGPARAMS,
                // TODO: Add more message IDs here as needed.
            };
            D3D11_INFO_QUEUE_FILTER filter = {};
            filter.DenyList.NumIDs = _countof(hide);
            filter.DenyList.pIDList = hide;
            d3dInfoQueue->AddStorageFilterEntries(&filter);
        }
    }
#endif

It's also important to not ignore the HRESULT return value that comes back from As. You should use SUCCEEDED or FAILED macro, or a fast-fail like ThrowIfFailed.

See ComPtr.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...