I made the following method for creating interface instance.
static IFBIndexItem* CreateFBIndexItemPtr()
{
IFBIndexItemPtr pFBComWrapper;
HRESULT hr = pFBComWrapper.CreateInstance(__uuidof(FBIndexItem));
if (FAILED(hr)) {
throw new _com_error(hr);
}
return pFBComWrapper;
}
It works fine, but since I have multiple interfaces, I want to create a template method. So here is the resulted method, but it throws “Class not registered” exception.
template<class T>
static T* CreateInterfacePtr()
{
_com_ptr_t <_com_IIID<T, &__uuidof(T)>> pFBComWrapper;
HRESULT hr = pFBComWrapper.CreateInstance(__uuidof(T));
if (FAILED(hr)) {
throw new _com_error(hr);
}
return pFBComWrapper;
}
I wonder why it doesn’t work correctly. Thanks.
The problem is you pass the UUID of the interface in place of the class id into
CreateIsntance().Of course
CreateInstance()will fail when used like that – there’s (normally) no COM-exposed class with the same id as the interface. Also more than one class can implement the same interface, so naturally you will want to be able to pass different class ids for the same interface.Hence you need to have two parameters in your function – the interface and the class id (or the class itself from which you can get the class id using
__uuidof).Also you have a serious ownership problem in your code. The function returns a raw pointer extracted from a smart pointer that is destroyed when function returns. This will likely lead to the object being released and the pointer becoming dangling.