Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check COM pointers for equality

Tags:

c++

com

If I have two COM interface pointers (i.e. ID3D11Texture2D), and I want to check if they are the same underlying class instance, can I compare the two pointers directly for equality? I have seen code where we cast it to something else before the comparison is done, so wanted to confirm.

BOOL IsEqual (ID3D11Texture2D *pTexture1, ID3D11Texture2D *pTexture2)
{
    if (pTexture1 == pTexture2)
    {
        return true;
    }
    else
    {
        return false;
    }
} 

Thanks.

like image 946
lancery Avatar asked Jan 10 '23 16:01

lancery


1 Answers

The correct COM way to do this is to query interface with IUnknown. A quote from the remarks here in MSDN:

For any one object, a specific query for the IUnknown interface on any of the object's interfaces must always return the same pointer value. This enables a client to determine whether two pointers point to the same component by calling QueryInterface with IID_IUnknown and comparing the results. It is specifically not the case that queries for interfaces other than IUnknown (even the same interface through the same pointer) must return the same pointer value.

So the correct code is

BOOL IsEqual (ID3D11Texture2D *pTexture1, ID3D11Texture2D *pTexture2)
{
    IUnknown *u1, *u2;

    pTexture1->QueryInterface(IID_IUnknown, &u1);
    pTexture2->QueryInterface(IID_IUnknown, &u2);

    BOOL areSame = u1 == u2;
    u1->Release();
    u2->Release();

    return areSame;
}

Update

  1. Added a call to Release so decrease reference counts. Thanks for the good comments.
  2. You can also use ComPtr for this job. Please look in MSDN.
like image 79
Alex Shtof Avatar answered Jan 18 '23 05:01

Alex Shtof