#include#include //Creating an instance of CComPtr CComPtr spObj; HRESULT hr = spObj.CoCreateInstance(__uuidof(SomeComponent)); if (FAILED(hr)) { //Handle creation failure } //Using the COM object int result = spObj->SomeMethod(argument);
CComPtrIn this example, we create a CComPtr object to manage an instance of the IUnknown interface. We then use the CoCreateInstance method to create a new instance of the SomeComponent object, and if successful, we check whether the spUnk object is not null. We created a nested scope and initialized another CComPtr object, spObj, to manage an instance of the ISomeInterface interface. We then called the QueryInterface method of spUnk to set spObj to point to the same COM object. After using spObj, it is released from memory automatically since it is declared within a nested scope. Finally, we release spUnk to release the remaining reference to the COM object. Package/Library: C++ ATL (Active Template Library)spUnk; HRESULT hr = spUnk.CoCreateInstance(__uuidof(SomeComponent)); if (hr == S_OK && spUnk) { { CComPtr spObj; hr = spUnk->QueryInterface(&spObj); //Use spObj } spUnk.Release(); }