What is the purpose of using the QueryInterface method? (Direct3D)
Asked Answered
E

1

9

i understand what the QueryInterface method actually does- it only returns a pointer to a specific interface. But my question is, why would i want to use this method?

I mean, what is the difference between

QueryInterface(__uuidof(IDXGIResource), (void**)&Resource)

and

IDXGIResource * Resource

aren't these pretty much the same? if so, why would i even need to use the method? For what reasons should i use it?

Efface answered 5/8, 2015 at 0:59 Comment(3)
Think "multiple inheritance". Given an object of one type, it allows you to query if it is also an object of another type.Patsy
Oh i see. So in a way, it's basically a pointer that points to different interfaces right? So if i did this device->CreateTexture2D(&SharedTextureDesc, NULL, &SharedTexture); SharedTexture->QueryInterface(__uuidof(IDXGIResource), (void**)&SharedResource); this would mean that, first of all, the SharedResource pointer will now point to the texture that SharedTexture points to right?Efface
You can think of QueryInterface as COMs equivalent of dynamic_cast, and remember that it can fail so be sure to check the HRESULT for failure. Rather than using QueryInterface directly, consider making use of the Microsoft::WRL::ComPtr smart-pointer and then As method which wraps this up in a more natural C++ syntax.Gunshy
A
13

COM assumes that a single object will provide multiple interfaces, i.e. the interfaces will be fine-grained and you'll want to use more than one of them at a time. QueryInterface is how you get a pointer to those other interfaces on an object.

Your examples are incomplete. The first doesn't show that QueryInterface is being called from an existing interface, and the second doesn't assign any value to the pointer (it's an uninitialized pointer). A practical example would combine the two:

IDXGIResource * Resource = NULL;
pInterface->QueryInterface(__uuidof(IDXGIResource), (void **)&Resource);

To be robust you should make sure that the QueryInterface call succeeded before you try to use the pointer.

if (SUCCEEDED(pInterface->QueryInterface(__uuidof(IDXGIResource), (void **)&Resource))
    Resource->DoSomething();
Argentic answered 5/8, 2015 at 3:54 Comment(1)
Thank you very much for that explanation!Efface

© 2022 - 2024 — McMap. All rights reserved.