[英]COM interop interface casting
Following this article , I have successfully translated C++ COM class/interface declaration into C# like this: 在本文之后 ,我已经成功地将C ++ COM类/接口声明转换为C#,如下所示:
[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? 我的问题是,考虑到
Foo
不实现IFoo
(即使在运行时, typeof(Foo).GetInterfaces()
为空)并且禁止用户定义的接口转换,这怎么可能起作用?
Is this some special handling reserved just for COM? 是否仅为COM保留一些特殊处理? What does the C# specification have to say about this?
C#规范对此要说些什么?
ComImport
types are treated differently compared to "normal" .NET classes, as they constitute a runtime-callable wrapper around an underlying COM coclass. 与“常规” .NET类相比,
ComImport
类型的处理方式有所不同,因为它们构成了围绕基础COM协同类的运行时可调用包装器。 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 method IUnknown.QueryInterface
. 将其中之一的实例强制转换为COM接口类型将透明地映射到对COM接口方法
IUnknown.QueryInterface
的对象实现的调用。
If QI for the requested interface succeeds at the COM level, then the C# cast will also succeed. 如果所请求接口的QI在COM级别成功,则C#强制转换也将成功。
Well, yes, casts for classes marked with ComImport
to COM interfaces result in a QueryInterface()
under the hood - that I guess is done inside the RCW. 好吧,是的,将标有
ComImport
类强制转换为COM接口会导致QueryInterface()
在幕后-我猜是在RCW内部完成的。
This way new
leads to CoCreateInstance()
being called and then the cast leads to QueryInterface()
being called. 这样,
new
导致调用CoCreateInstance()
,然后强制转换导致调用QueryInterface()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.