George2
February 11th, 2008, 03:47 AM
Hello everyone,
My question is whether my understanding of the solution to type safe issue in CoCreateInstance is correct. There is type safe issue in CoCreateInstance,
http://msdn2.microsoft.com/en-us/library/ms686615.aspx
STDAPI CoCreateInstance(
REFCLSID rclsid,
LPUNKNOWN pUnkOuter,
DWORD dwClsContext,
REFIID riid,
LPVOID * ppv
);
which means the riid and ppv may not conform to each other, for example, we have a IY* variable pIY and wants to get IZ type interface, CoCreateInstance (rclsid, pUnkOuter, dwClsContext, IID_IZ, &pIY);
To solve this issue, the solution from Inside COM is,
1. Define a template class smart pointer IComPtr<T, IID* iid>, where T is type of interface to wrap, iid is its related interface IID;
2. Define a function in the template class called CreateInstance, the implementation is,
2.1 invoke Release(); // release previous held pointer
2.2 invoke CoCreateInstance (rclsid, pUnkOuter, dwClsContext, *iid, &m_pI); // m_pI the wrapped interface pointer member variable for the smart pointer template class.
I think why the solution works, is because in the creation of the template class, the interface type T and iid is matched (example, through constructor or assignment operator), so when using the internal variable *iid and m_pI to invoke CoCreateInstance, the type always match (Interface ID and Interface type).
Is my understanding correct?
thanks in advance,
George
My question is whether my understanding of the solution to type safe issue in CoCreateInstance is correct. There is type safe issue in CoCreateInstance,
http://msdn2.microsoft.com/en-us/library/ms686615.aspx
STDAPI CoCreateInstance(
REFCLSID rclsid,
LPUNKNOWN pUnkOuter,
DWORD dwClsContext,
REFIID riid,
LPVOID * ppv
);
which means the riid and ppv may not conform to each other, for example, we have a IY* variable pIY and wants to get IZ type interface, CoCreateInstance (rclsid, pUnkOuter, dwClsContext, IID_IZ, &pIY);
To solve this issue, the solution from Inside COM is,
1. Define a template class smart pointer IComPtr<T, IID* iid>, where T is type of interface to wrap, iid is its related interface IID;
2. Define a function in the template class called CreateInstance, the implementation is,
2.1 invoke Release(); // release previous held pointer
2.2 invoke CoCreateInstance (rclsid, pUnkOuter, dwClsContext, *iid, &m_pI); // m_pI the wrapped interface pointer member variable for the smart pointer template class.
I think why the solution works, is because in the creation of the template class, the interface type T and iid is matched (example, through constructor or assignment operator), so when using the internal variable *iid and m_pI to invoke CoCreateInstance, the type always match (Interface ID and Interface type).
Is my understanding correct?
thanks in advance,
George