Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ComPtr vs CComPtr, As vs QueryInterface

Tags:

c++

atl

wrl

I just want know what exact difference between ComPtr and CComPtr, and whether ComPtr::As() is analogue of CComPtr::QueryInterface()? I read documentation of both, but there is no clear answer to the question...

like image 923
Olga Pshenichnikova Avatar asked Mar 06 '20 09:03

Olga Pshenichnikova


2 Answers

what exact difference between ComPtr and CComPtr

They are simply COM interface smart wrappers from different frameworks. ComPtr is part of the Windows Runtime C++ Template Library (WRL). CComPtr is part of the Active Template Library (ATL) . They serve similar purposes for their respective frameworks - to provide automated reference counting and refcount-safe typecasting. But you should not mix them interchangeably. If you are writing WRL code, use ComPtr. If you are writing ATL code, use CComPtr.

whether ComPtr::As() is analogue of CComPtr::QueryInterface()?

Yes, because As() simply calls QueryInterface() internally.

like image 169
Remy Lebeau Avatar answered Oct 22 '22 17:10

Remy Lebeau


What's nice about those class is you have the source, in C:\Program Files (x86)\Windows Kits\10\Include\10.0.18362.0\winrt\wrl\client.h (adapt to your context and Visual Studio version):

template <typename T>
class ComPtr
{
public:
    typedef T InterfaceType;

    ...

    // query for U interface
    template<typename U>
    HRESULT As(_Inout_ Details::ComPtrRef<ComPtr<U>> p) const throw()
    {
        return ptr_->QueryInterface(__uuidof(U), p);
    }

    // query for U interface
    template<typename U>
    HRESULT As(_Out_ ComPtr<U>* p) const throw()
    {
        return ptr_->QueryInterface(__uuidof(U), reinterpret_cast<void**>(p->ReleaseAndGetAddressOf()));
    }

    // query for riid interface and return as IUnknown
    HRESULT AsIID(REFIID riid, _Out_ ComPtr<IUnknown>* p) const throw()
    {
        return ptr_->QueryInterface(riid, reinterpret_cast<void**>(p->ReleaseAndGetAddressOf()));
    }

    ...
};

So, yes, As basically calls QueryInterface underneath.

like image 3
Simon Mourier Avatar answered Oct 22 '22 16:10

Simon Mourier