ComPtrmyInstance; HRESULT hr = CoCreateInstance(CLSID_MyClass, nullptr, CLSCTX_INPROC_SERVER, IID_IMyInterface, (void**)myInstance.GetAddressOf()); if (FAILED(hr)) { // handle error }
IMyInterface* rawInstance = // get raw pointer to existing object ComPtrmyInstance = rawInstance;
ComPtrIn general, the ComPtr class is used to simplify the lifetime management of COM objects in C++ code. It automatically adds reference counting to the underlying COM object, so you don't have to worry about manually calling AddRef and Release. It also provides automatic null checking, so you don't have to check for null before calling methods. The ComPtr class is part of the Windows Runtime C++ Template Library (WRL) package library.myInstance = // get ComPtr to object HRESULT hr = myInstance->MyMethod(arg1, arg2); if (FAILED(hr)) { // handle error }