当我有一个像IMediaSample
这样的接口的实例时,我可以将它转换为实现此接口的类,如CMediaSample
吗?如果是,怎么样?
答案 0 :(得分:1)
虽然您无法投射接口指针以进入基类(因为您提供的界面不一定是您实施的界面),您< em>可以为QueryInterface定义一个自定义IID,您的QI实现将返回&#39; this&#39;。 E.g:
STDMETHOD(QueryInterface)(IN REFIID riid, OUT void** ppv)
{
*ppv = NULL;
// IUnknown can require extra casting to pick out a specific IUnknown instance
// otherwise compiler will complain about an ambiguous cast. Any IUnknown will do,
// we know they're all the same implementation, so even casting to CFooHandler then IUnknown is fine here.
// Here am assuming that CUnknown implements IUnknown
if(riid == __uuidof(IUnknown))
*ppv = static_cast<IUnknown*>(static_cast<CUnknown*>(this));
else if(riid == __uuidof(IFoo))
*ppv = static_cast<IFoo*>(this);
else if(riid == __uuidof(IBar))
*ppv = static_cast<IBar*>(this);
else if(riid == __uuidof(IThis))
*ppv = this;
else
return E_NOINTERFACE;
}
这项技术已经存在了一段时间; Chris Sells创建了一个名为COM_INTERFACE_ENTRY_THIS的宏,这使得在ATL COM接口映射中实现它变得微不足道。
显然,这对于撕下接口不起作用,但如果您正在那,那么您将知道QI的基本接口,然后是实现