从 COM 类继承
我正在 Visual Studio 2005 中使用纯非托管项目 (C++)。我有一个来自第三方的 COM 类,位于 OCX 文件中。此类是一个控件(“小部件”)。我一直通过使用“从 Typelib 向导添加类”生成的 IDispatch 包装类来使用它。
我想以几种方式扩展此类,并且公共继承比组合更实用(我希望派生对象公开父类所做的每个方法)。派生类还应该可以作为 COM 组件使用。
我可以这样做吗?如果是积极的,我怎样才能做到这一点?
I'm working in Visual Studio 2005 with a pure unmanaged project (C++). I have a COM class, from a third party, in a OCX file. This class is a control ("widget"). I've been using it through a IDispatch wrapper class generated using the Add Class from Typelib Wizard.
I would like to extend this class in a few ways and public inheritance would be way more practical than compositing (I want the derived object to expose every single method that the parent class does). The derived class should also be available as a COM component.
Can I do this? If positive, how can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无法像在 C++ 中那样从 COM 类继承。不过,有一些解决方法:
仅当您想要添加时 COM 聚合才有用 现有 COM 类的接口(带有实现)。您无法拦截对聚合对象的调用。
转发意味着,如果您有一个接口
IExistingInterface
,则您可以实现自己的类,该类实现IExistingInterface
。在您的类中,您保留对要“继承”的对象实例的引用。在IExistingInterface
的实现中,您可以根据需要将调用转发给“继承的”对象。这种方法可以让您完全控制。示例:(伪代码!)
编辑:
我强烈建议您使用 ATL 来创建 COM 组件。在这种情况下,请在 FinalConstruct() 而不是 C++ 构造函数中构造“继承”对象。
It is not possible to inherit from COM classes as you can in C++. There are workarounds though:
COM aggregates is only useful if you want to add an interface (with implementation) to an existing COM class. You cannot intercept calls to the aggregated object.
Forwarding means that if you have an interface
IExistingInterface
, you implement your own class that implementsIExistingInterface
. In your class you keep a reference to an instance of the object you want to "inherit" from. In your implementation ofIExistingInterface
, you forward calls as appropriate to the "inherited" object. This method gives you total control.Example: (pseudo-code!)
Edit:
I really recommend that you use ATL to create your COM component. In that case, construct the "inherited" object in
FinalConstruct()
rather than the C++ constructor.您可以创建一个从第一个接口派生的新接口。您的 QueryInterface 函数需要响应两个 GUID 并提供正确的指针。完成此操作后,让您的具体类实现函数的超集(即所有第二个接口,包括从第一个接口继承的所有内容。)
如果您的具体类也将从库中的具体类继承,那么您'我们将拥有钻石继承模式。您可以搜索解决方案,我从这里开始:钻石继承 (C++)
You can create a new interface that derives from the first. Your QueryInterface function will need to respond to both GUIDs and deliver the proper pointer. Once you've done that, have your concrete class implement the superset of the functions (i.e. all of the second interface, including everything inherited from the first.)
If your concrete class will also inherit from a concrete class in the library, you're going to have a diamond inheritance pattern. You can search for solutions to that, I'd start here: Diamond inheritance (C++)