是否可以将接口(interface)指针分配给另一个接口(interface)指针,其中两个接口(interface)指针都指向同一个类。 下面是我的 Test.h 和 Test.cpp 代码
class Test
{
ITestPtr testPtr;
ITestSecondPtr secondPtr;
};
Test:: Test()
{
testPtr.CreateInstance(__uuidof(MyNamespace::MyClass));
secondPtr=testPtr;
}
这里我的 ITestPtr 和 ITestSecondPtr 指向相同的 C# 类 MyClass。 因此,为了避免 C# 类的双重初始化,我将 testPtr 分配给 secondPtr。 构建成功。但是运行时抛出访问冲突异常。如果有任何解决方案,请告诉我。
最佳答案
没有。不可能将指向一个 COM 接口(interface)的指针分配给另一个。当您为 IUnknown 查询接口(interface)时,您将始终获得指向实现对象的相同指针。但是当你查询一个特定的接口(interface)时,你会得到不同的指针。
原因是指针指向VMT指针。当您对 IUnknown 有不同的继承时,您需要不同的 VMT。这就是为什么 QueryInterface 必须在不同的地址选择正确的 VMT。
约定总是返回相同的 IUnkown 指针的原因是,这允许检查对象的身份,尽管您为不同的接口(interface)获得不同的指针。
所以您要求的解决方案:不要(隐式)强制转换 COM 接口(interface)指针。使用 QueryInterface()
获取正确的指针。
更多详情here .
关于c# - 在 C++ 中将一个接口(interface)指针分配给另一个接口(interface)指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19558339/