COM 互操作接口转换
按照本文,我已成功将 C++ COM 类/接口声明转换为C# 像这样:
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid(IfaceGuid)]
public interface IFoo
{
void Bar();
}
[ComImport, Guid(ClassGuid)]
public class Foo
{ }
我这样使用它:
var foo = new Foo();
var ifoo = (IFoo)foo;
ifoo.Bar();
我的问题是,考虑到 Foo
没有实现 IFoo
(即使在运行时,typeof(Foo).GetInterfaces()
为空)并且禁止用户定义的接口转换?
这是专门为 COM 保留的特殊处理吗? C# 规范对此有何规定?
Following this article, I have successfully translated C++ COM class/interface declaration into C# like this:
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid(IfaceGuid)]
public interface IFoo
{
void Bar();
}
[ComImport, Guid(ClassGuid)]
public class Foo
{ }
I use it like this:
var foo = new Foo();
var ifoo = (IFoo)foo;
ifoo.Bar();
My question is, how can this possibly work, considering that Foo
doesn't implement IFoo
(even at runtime, typeof(Foo).GetInterfaces()
is empty) and that user-defined conversions to interfaces are forbidden?
Is this some special handling reserved just for COM? What does the C# specification have to say about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与“普通”.NET 类相比,ComImport 类型的处理方式有所不同,因为它们构成了底层 COM 组件类的运行时可调用包装器。将其中之一的实例转换为 COM 接口类型会透明地映射到对 COM 接口方法
IUnknown.QueryInterface
的对象实现的调用。如果所请求接口的 QI 在 COM 级别成功,则 C# 转换也将成功。
ComImport
types are treated differently compared to "normal" .NET classes, as they constitute a runtime-callable wrapper around an underlying COM coclass. Casting an instance of one of these into a COM interface type is transparently mapped into a call to the object's implementation of the COM interface methodIUnknown.QueryInterface
.If QI for the requested interface succeeds at the COM level, then the C# cast will also succeed.
嗯,是的,将带有
ComImport
标记的类转换为 COM 接口会在幕后产生QueryInterface()
- 我猜这是在 RCW 内部完成的。这样,
new
会导致CoCreateInstance()
被调用,然后强制转换会导致QueryInterface()
被调用。Well, yes, casts for classes marked with
ComImport
to COM interfaces result in aQueryInterface()
under the hood - that I guess is done inside the RCW.This way
new
leads toCoCreateInstance()
being called and then the cast leads toQueryInterface()
being called.