为COM事件设置处理程序时出现InvalidCastException

时间:2010-10-04 19:59:52

标签: c# events com iconnectionpoint

我有一个非托管C ++ COM服务器,它设置为触发事件,我正试图从我的C#app处理这些事件。

但是,在设置处理程序时会出现InvalidCastException

myCOMObj.MyCOMEvent += new MyCOMSource_MyCOMEventHandler(handler);

堆栈跟踪显示:

  

指定的演员表无效。在   System.Runtime.InteropServices.ComTypes.IConnectionPoint.Advise(Object pUnkSink,Int32& dwCookie)at at   MyCOMSource_EventProvider.add_MyCOMEvent(MyCOMSource_MyCOMEventHandler)at at   MyCOMSource_Event.add_MyCOMEvent(MyCOMSource_MyCOMEventHandler)

我尝试过设置我自己的IConnectionPoint

IConnectionPointContainer connectionPointContainer = (IConnectionPointContainer)myCOMObj;
Guid sourceGuid = typeof(MyCOMSource).GUID;
IConnectionPoint connectionPoint;
connectionPointContainer.FindConnectionPoint(ref sourceGuid, out connectionPoint);
int cookie;
connectionPoint.Advise(myEventNotifier, out cookie);

其中myEventNotifier是如下定义的类的对象:

[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class EventNotifier : MyCOMSource
...

但是我在connectionPoint.Advise处获得了与堆栈跟踪

相同的InvalidCastException
  

指定的演员表无效。在System.Runtime.InteropServices.ComTypes.IConnectionPoint.Advise(Object pUnkSink,Int32& pdwCookie)

我认为这是客户端的一个问题,因为当我尝试做自己的ConnnectionPoint时,以及当我让框架为我做这个时,一致的行为。但是如果它是服务器端的东西:

在COM服务器端,我已将其声明为

coclass MyCOMCoClass
{
    [default] dispinterface MyCOMInterface;
    [default, source] dispinterface MyCOMSource;
};

我的课程中也有CONNECTION_MAPCONNECTION_PART个宏。

可能会发生什么,我该怎么调试呢?

1 个答案:

答案 0 :(得分:1)

MyEventHandler的GUID必须等于sourceGuid,并且当前程序集HAS必须是COMVisible。