COM 互操作接口转换

发布于 2024-10-31 13:50:41 字数 578 浏览 0 评论 0原文

按照本文,我已成功将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

2024-11-07 13:50:41

与“普通”.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 method IUnknown.QueryInterface.

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

最冷一天 2024-11-07 13:50:41

嗯,是的,将带有 ComImport 标记的类转换为 COM 接口会在幕后产生 QueryInterface() - 我猜这是在 RCW 内部完成的。

这样,new 会导致 CoCreateInstance() 被调用,然后强制转换会导致 QueryInterface() 被调用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文