简体   繁体   English

C#COM接口继承

[英]C# COM Interface Inheritance

I have the following (DirectShow related) COM interface in C++ that I need to call in C#. 我有以下C ++中与DirectShow相关的COM接口,需要在C#中调用。

[uuid("...")] : public IUnknown
interface IBar
{
    STDMETHOD(Bar)(void);
}

[uuid("...")]
interface IFoo : public IBar
{
    STDMETHOD(Foo)(void);
}

I declared this in C# as the following but it crashes out with Access Violation when IFoo.Foo() is called. 我在C#中声明了以下内容,但是在调用IFoo.Foo()时,它因访问冲突而崩溃。 Works fine with IBar.Bar() is called though. 可以与IBar一起正常工作,但是会调用Bar()。 What is the correct way to write the equivalent interface in C#? 用C#编写等效接口的正确方法是什么?

[ComImport, Guid("...)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[SuppressUnmanagedCodeSecurity]
public interface IBar
{
    [PreserveSig] int Bar(); // Calling this is OK
}

[ComImport, Guid("...)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[SuppressUnmanagedCodeSecurity]
public interface IFoo : IBar
{
    [PreserveSig] int Foo(); // Calling this crashes
}

The vtables must be incompatible in C# vs C++ for inherited COM interface. 对于继承的COM接口,vtable在C#与C ++中必须不兼容。 Is there a way to tell C# to adhere to the C++ declaration? 有没有办法告诉C#遵守C ++声明?

Your C# declaration of IFoo should look like this: 您的IFoo C#声明应如下所示:

[ComImport, Guid("...)]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[SuppressUnmanagedCodeSecurity]
public interface IFoo
{
    [PreserveSig] int Bar(); // Calling this is OK
    [PreserveSig] int Foo(); // Calling this should also be OK
}

In other words, you should replicate methods (and v-table layout) of IBar for IFoo instead of deriving from it, to make the .NET COM interop marshaller happy. 换句话说,您应该为IFoo复制IBar方法(和v-表布局),而不是从中继承,以使.NET COM互操作编组器感到高兴。 The same is possible in C++, although it's more natural to use C++ inheritance there. 尽管在C ++中使用C ++继承更为自然,但在C ++中也可以做到这一点。 For .NET COM interop though, it's a necessity. 对于.NET COM互操作,这是必需的。

This technique is widely used in the .NET Reference Source, eg for IOleInPlaceActiveObject , which is derived from IOleWindow . .NET参考源中广泛使用了此技术,例如IOleInPlaceActiveObject (它是从IOleWindow派生的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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