C#到VB6 COM事件(“对象或类不支持事件集”)

时间:2009-05-19 06:53:07

标签: c# events vb6 interop delegates

真的把这头发拉出来......

我有一个C#项目,其接口定义为:

/* Externally Accessible API */
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ISerial
{
    [DispId(1)]
    bool Startup();

    [DispId(2)]
    bool Shutdown();

    [DispId(3)]
    bool UserInput_FloorButton(int floor_number);

    [DispId(4)]
    bool Initialize();
}

/* Externally Accesssible Event API */
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ISerialEvent
{
    [DispId(5)]
    void DataEvent();
}

[ComSourceInterfaces(typeof(ISerialEvent), typeof(ISerial))]
[ClassInterface(ClassInterfaceType.None)]
public class SerialIface : ISerial
{
    public delegate void DataEvent();
    public event DataEvent dEvent;

    public bool Initialize()
    {
        //testing the event callback
        if (dEvent != null)
        {
            dEvent();
        }
    }
    ...
}

VB6代码如下:

Private WithEvents objSerial As SerialIface

Private Sub objSerial_DataEvent()
    'do something happy'
End Sub

Public Sub Class_Initialize()
    Set objSerial = New SerialIface  '<---this is the line that fails'
    Call objSerial.Initialize  '<--Initialize would trigger DataEvent, if it got this far'
End Sub

嗯,正常的API类型函数似乎正在工作(如果我声明没有WithEvents关键字的objSerial),但我不能在我的生活中让“DataEvent”工作。它失败,“对象或类不支持事件集”消息。

我原本把这两个接口混为一谈,但后来C#抱怨DataEvent没有在类中定义。目前的方式,我能够在VB6对象浏览器中完美地查看所有API和一个事件 - 一切看起来都在那里......我只是无法让它真正起作用!

我确信我错过了一些显而易见的事情或做了一些愚蠢的事情 - 但我对整个互操作业务都很陌生,所以它只是完全逃避我。

帮助!

2 个答案:

答案 0 :(得分:7)

请看这篇文章here

具体来说,您似乎错过了一个类似于此的声明。

[Guid("9E5E5FB2-219D-4ee7-AB27-E4DBED8E123E"),
    ClassInterface(ClassInterfaceType.None),
    ComSourceInterfaces(typeof(DBCOM_Events))]
    public class DBCOM_Class : DBCOM_Interface
    {

你有这个部分

// // Events interface Database_COMObjectEvents 
[Guid("47C976E0-C208-4740-AC42-41212D3C34F0"), 
InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface DBCOM_Events 
{
}

但是没有第二个,COM对象的vtable和typelib没有使用VB6(或其他COM消费者)所需的事件映射。

您可以使用Google搜索字词“com event”c#并获得其他一些好结果。

答案 1 :(得分:3)

你的帖子确实引导我找到解决方案 - 谢谢!

毫不奇怪,事实证明这是一个错字。

/* Externally Accesssible Event API */
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ISerialEvent
{
    [DispId(5)]
    void DataEvent();
}

应该是

/* Externally Accesssible Event API */
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface ISerialEvent
{
    [DispId(5)]
    void dEvent();
}

我使用委托而不是事件

来定义界面

再次,谢谢你的帮助!