ComPtr vs CComPtr, As vs QueryInterface
Asked Answered
E

2

8

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...

Evanthe answered 6/3, 2020 at 9:13 Comment(0)
M
6

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.

Mucoprotein answered 6/3, 2020 at 17:57 Comment(0)
T
3

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.

Taphole answered 6/3, 2020 at 9:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.