简体   繁体   中英

COM interop interface casting

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?

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 method IUnknown.QueryInterface .

If QI for the requested interface succeeds at the COM level, then the C# cast will also succeed.

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.

This way new leads to CoCreateInstance() being called and then the cast leads to QueryInterface() being called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM