2014-09-30 182 views
1

我需要在C#中调用C++中的以下(DirectShow相关)COM接口。C#COM接口继承

我在C#中声明如下,但是当调用IFoo.Foo()时,它与Access Violation一起崩溃。工作正常与IBar.Bar()被称为虽然。在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 
} 

的虚函数表必须是对C++对继承COM接口在C#不相容。有没有办法告诉C#遵守C++声明?

回答

1

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 
} 

换句话说,你应该复制的IBar方法(和v表布局)IFoo,而不是从中获取的,以使。 NET COM interop编组很高兴。在C++中也是如此,尽管在那里使用C++继承更自然。对于.NET COM互操作,这是必要的。

该技术被广泛用于.NET Reference Source中,例如,为IOleInPlaceActiveObject,它来源于IOleWindow