c# - 将 C# COM 服务器事件公开给 Delphi 客户端应用程序

标签 c# delphi com .net-4.0

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

C# component events?

C# - writing a COM server - events not firing on client

但是,对他们有用的方法对我不起作用。类型库文件没有任何事件定义提示,因此 Delphi 看不到它。如您所料,该类适用于其他 C# 应用程序。

COM 服务器工具:

  • Visual Studio 2010
  • .NET 4.0

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");
        }
    }
}

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

如果有任何建议或文章可供阅读,我将不胜感激。

谢谢!

最佳答案

经过反复试验,我终于解决了这个问题。我需要对 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 事件的定义。

Step-By-Step blog post on how to do this

关于c# - 将 C# COM 服务器事件公开给 Delphi 客户端应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2867582/

相关文章:

c# - 使用 TreeView 在 WPF 中获取 XML 属性

c# - 验证特定字符串值的模型

delphi - 索引列表越界(0) Delphi

delphi - 使用中的问题 已弃用或实验指令

java - 如何在 Linux (Ubuntu) 中使用 COM

c# - 机器中的多任务与多进程

c# - 在运行时更新 dbfirst Entity Framework 模型的方法

delphi - Firebird SQL 脚本命令字符串限制

windows - 将 COM 对象导入 COM+ 应用程序,同时保留直接访问 COM 对象?

c# - Excel Interop 和 CSV 文件的日期转换问题