如何在C ++中实现多个COM接口? [英] How does implementing multiple COM interfaces work in C++?

查看:73
本文介绍了如何在C ++中实现多个COM接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解有关浏览器帮助器对象的此示例代码.

I am trying to understand this example code regarding Browser Helper Objects.

在内部,作者实现了一个单独的类,该类公开了多个接口(IObjectWithSite,IDispatch).

Inside, the author implements a single class which exposes multiple interfaces (IObjectWithSite, IDispatch).

他的QueryInterface函数执行以下操作:

His QueryInterface function performs the following:

if(riid == IID_IUnknown) *ppv = static_cast<BHO*>(this);
else if(riid == IID_IObjectWithSite) *ppv = static_cast<IObjectWithSite*>(this);
else if (riid == IID_IDispatch) *ppv = static_cast<IDispatch*>(this);

我了解到,从C角度来看,接口指针只是指向VTables的指针.因此,我认为C ++能够使用static_cast返回任何已实现接口的VTable.

I have learned that from a C perspective, interface pointers are just pointers to VTables. So I take it to mean that C++ is capable of returning the VTable of any implemented interface using static_cast.

这是否意味着以这种方式构造的类在内存中有一堆VTable(IObjectWithSite,IDispatch等)?C ++对不同接口(它们每个都有QueryInterface,AddRef和Release函数)上的名称冲突有什么作用,我可以为每个接口实现不同的方法吗?

Does this mean that a class constructed in this way has a bunch of VTables in memory (IObjectWithSite, IDispatch, etc)? What does C++ do with the name collisions on the different interfaces (they each have a QueryInterface, AddRef and Release function), can I implement different methods for each of these?

推荐答案

是的,有多个v表,每个继承的接口一个.static_cast<>返回它.编译器确保共享继承接口中的通用方法,并使用指向同一函数的指针填充每个v-table插槽.因此,您只需要AddRef,Release,QueryInterface的一种实现.就是您想要的.这些都不是意外.

Yes, there are multiple v-tables, one for each inherited interface. The static_cast<> returns it. The compiler makes sure that common methods in the inherited interfaces are shared, it fills each v-table slot with the a pointer to the same function. So you only need one implementation of AddRef, Release, QueryInterface. Just what you want. None of this is an accident.

仅当协类使用您不想要提供相同实现的相同方法实现多个接口时,这才是问题.IConnectionPoint :: Advise()方法是一个臭名昭著的示例.还是DAdvise()?不幸的是,我不记得它遇到了什么以及如何解决,它已被ATL Internals涵盖.顺便说一句好书.

This is only ever a problem when a coclass implements multiple interfaces with the same method that you don't want to give the same implementation. The IConnectionPoint::Advise() method is a notorious example. Or was it DAdvise()? Unfortunately, I don't remember what it clashed with and how it was solved, it was covered by ATL Internals. Very good book btw.

这篇关于如何在C ++中实现多个COM接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆