将C#COM服务器事件暴露给Delphi客户端应用程序
我的问题与这两个非常相似:
C#组件事件?
C# – 编写COM服务器 – 未在客户端上触发的事件
然而,对他们有用的不适合我。 类型库文件没有任何事件定义提示,因此Delphi没有看到它。 正如您所料,该类适用于其他C#应用程序。
COM服务器工具:
- Visual Studio 2010
- .NET 4.0
Delphi应用程序:
- Delphi 2010
- delphi7
这是代码的简化版本:
/// /// Call has arrived delegate. /// [ComVisible(false)] public delegate void CallArrived(object sender, string callData); /// /// Interface to expose SimpleAgent events to COM /// [ComVisible(true)] [GuidAttribute("1FFBFF09-3AF0-4F06-998D-7F4B6CB978DD")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IAgentEvents { /// /// Handles incoming calls from the predictive manager. /// ///The class that initiated this event ///The data associated with the incoming call. [DispId(1)] void OnCallArrived(object sender, string callData); } /// /// Represents the agent side of the system. This is usually related to UI interactions. /// [ComVisible(true)] [GuidAttribute("EF00685F-1C14-4D05-9EFA-538B3137D86C")] [ClassInterface(ClassInterfaceType.None)] [ComSourceInterfaces(typeof(IAgentEvents))] public class SimpleAgent { /// /// Occurs when a call arrives. /// public event CallArrived OnCallArrived; public SimpleAgent() {} public string AgentName { get; set; } public string CurrentPhoneNumber { get; set; } public void FireOffCall() { if (OnCallArrived != null) { OnCallArrived(this, "555-123-4567"); } } }
类型库文件具有属性和方法的定义,但没有可见的事件。 我甚至在Delphi的查看器中打开了类型库以确保它。 Delphi应用程序可以很好地查看和使用任何属性,方法和函数。 它只是没有看到事件。
我会很感激任何指针或文章阅读。
谢谢!
经过多次试验和错误,我终于得到了解决。 我需要在C#代码上更改两件事。
1)[ClassInterface(ClassInterfaceType.None)]需要更改为[ClassInterface(ClassInterfaceType.AutoDual)]
2)作为事件源的类需要从MarshalByRefObjectinheritance。 如果在源类中完成任何线程,这会有所帮助。
我在Delphi方面只需要一件事。 我需要确保选中“Generate Component Wrapper”复选框。 这就是在Delphi上实际构建事件脚手架的内容。
这是你在Delphi 7中的表现:
- 从菜单项目 – >导入类型库中选择
- 确保选中“Generate Component Wrapper”
- 从列表中选择COM类
- 单击“添加单位”按钮
新单元将具有COM事件的定义。
关于如何执行此操作的分步博客文章