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?

  • Think "multiple inheritance". Given an object of one type, it allows you to query if it is also an object of another type. – Jonathan Potter Aug 05 '15 at 01:06
  • 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? – Soon_to_be_code_master Aug 05 '15 at 01:16
  • 2
    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](https://github.com/Microsoft/DirectXTK/wiki/ComPtr) smart-pointer and then ``As`` method which wraps this up in a more natural C++ syntax. – Chuck Walbourn Aug 05 '15 at 04:23

1 Answers1

12

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();
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622