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?
QueryInterface is a mechanism in COM (microsoft's Component Object Model) for determining if a known component supports a specific interface. You use the current interface pointer (usually IUnknown), and "query" the interface by passing an interface ID to it.
In this article Regardless of implementation, this method queries an object using the IID of the interface to which the caller wants a pointer. If the object supports that interface, QueryInterface retrieves a pointer to the interface, while also calling AddRef . Otherwise, it returns the E_NOINTERFACE error code.
IUnknown interface (unknwn. Enables clients to get pointers to other interfaces on a given object through the QueryInterface method, and manage the existence of the object through the AddRef and Release methods. All other COM interfaces are inherited, directly or indirectly, from IUnknown.
The riid parameter is the GUID that identifies the interface you are asking for. The data type REFIID is a typedef for const GUID& . Notice that the class identifier (CLSID) is not required, because the object has already been created. Only the interface identifier is necessary.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With