将C#COM服务器事件暴露给Delphi客户端应用程序

Hec*_* Jr 4 c# delphi com .net-4.0

我的问题与这两个问题非常相似:

C#组件事件?

C# - 编写COM服务器 - 未在客户端上触发的事件

然而,对他们有用的东西并不适合我.类型库文件没有任何事件定义提示,因此Delphi没有看到它.正如您所料,该类适用于其他C#应用程序.

COM服务器工具:

  • Visual Studio 2010
  • .NET 4.0

Delphi应用程序:

  • Delphi 2010
  • 德尔福7

这是代码的简化版本:

 /// <summary>
/// Call has arrived delegate.
/// </summary>
[ComVisible(false)]
public delegate void CallArrived(object sender, string callData);

/// <summary>
/// Interface to expose SimpleAgent events to COM
/// </summary>
[ComVisible(true)]
[GuidAttribute("1FFBFF09-3AF0-4F06-998D-7F4B6CB978DD")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IAgentEvents
{
    ///<summary>
    /// Handles incoming calls from the predictive manager.
    ///</summary>
    ///<param name="sender">The class that initiated this event</param>
    ///<param name="callData">The data associated with the incoming call.</param>
    [DispId(1)]
    void OnCallArrived(object sender, string callData);
}

/// <summary>
/// Represents the agent side of the system. This is usually related to UI interactions.
/// </summary>
[ComVisible(true)]
[GuidAttribute("EF00685F-1C14-4D05-9EFA-538B3137D86C")]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(IAgentEvents))]
public class SimpleAgent
{
    /// <summary>
    /// Occurs when a call arrives.
    /// </summary>
    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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

类型库文件具有属性和方法的定义,但没有可见的事件.我甚至在Delphi的查看器中打开了类型库以确保它.Delphi应用程序可以很好地查看和使用任何属性,方法和函数.它只是没有看到事件.

我很感激任何指针或文章阅读.

谢谢!

Hec*_* Jr 5

经过多次试验和错误,我终于得到了解决.我需要在C#代码上更改两件事.

1)[ClassInterface(ClassInterfaceType.None)]需要更改为[ClassInterface(ClassInterfaceType.AutoDual)]

2)作为事件源的类需要从MarshalByRefObject继承.如果在源类中完成任何线程,这会有所帮助.

我在Delphi方面只需要一件事.我需要确保选中"Generate Component Wrapper"复选框.这就是在Delphi上实际构建事件脚手架的内容.

这是你在Delphi 7中的表现:

  1. 从菜单项目 - >导入类型库中选择
  2. 确保选中"Generate Component Wrapper"
  3. 从列表中选择COM类
  4. 单击"添加单位"按钮

新单元将具有COM事件的定义.

关于如何执行此操作的分步博客文章