使用实现多个接口的coclass

Using coclass that implements multiple interfaces

本文关键字:接口 coclass 实现      更新时间:2023-10-16

我正在编写一个C++/CLI应用程序,该应用程序使用了一个提供多个类的COM dll。它们中的大多数实现了许多接口。我想知道如何访问各个接口的方法。例如,当我查看类型库时,其中一个类被定义为:

coclass FWFile {
    [default] interface IFWFile;
    interface _IFWFileInternal;
    [default, source] interface _FWFileEvents;
    interface CStatistics;
    interface IFWFile2;
    interface IFWFile3;
    interface IFWFile4;
};

当我创建这种类型的对象时,它似乎实现了IFWFile接口。但是,我想使用IFWFile2中的方法。我可以简单地创建一个IFWFile2类型的对象并强制转换它吗?

IFWFile2 file2 = (IFWFile2)file1;

使用CoCreateInstance()时,可以指定从新创建的对象中检索哪个接口。如果需要多个接口,请在调用CoCreateInstance()时检索一个,并使用QueryInterface()检索其他接口。不要忘记为每次成功的接口检索调用Release()

只是不要C样式强制转换COM指针-接口不能保证按照类型库中指定的顺序,并且不能保证实际类实际实现了接口。始终使用QueryInterface()从COM对象中检索接口指针。