【问题标题】:InvalidCastException when setting up handler for COM event为 COM 事件设置处理程序时出现 InvalidCastException
【发布时间】:2010-10-04 19:59:51
【问题描述】:

我有一个设置为触发事件的非托管 C++ COM 服务器,我正在尝试从我的 C# 应用程序处理这些事件。

但是,我在设置处理程序时收到 InvalidCastException

myCOMObj.MyCOMEvent += new MyCOMSource_MyCOMEventHandler(handler);

堆栈跟踪显示:

指定的演员表无效。在 System.Runtime.InteropServices.ComTypes.IConnectionPoint.Advise(对象 pUnkSink,Int32& dwCookie)在 MyCOMSource_EventProvider.add_MyCOMEvent(MyCOMSource_MyCOMEventHandler) 在 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(对象 pUnkSink, Int32& pdwCookie)

我假设这是客户端的一个问题,因为当我尝试做我自己的 ConnnectionPoint 工作以及让框架为我做这件事时的一致行为。但万一是服务器端的东西:

在 COM 服务器端我已经这样声明了

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

我的课堂上也有 CONNECTION_MAPCONNECTION_PARTmacros。

可能发生了什么,我该如何调试?

【问题讨论】:

    标签: c# events com iconnectionpoint


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-14
      • 2018-04-03
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 2018-05-21
      • 1970-01-01
      相关资源
      最近更新 更多