繁体   English   中英

在 Delphi (COM) 中使用来自 C# DLL 的事件

[英]using events from C# DLL in Delphi (COM)

我有一个用 C# 编写的 DLL,我想在我的 Delphi 应用程序中使用它。

我能够将 DLL 正确(使用其 TLB 文件)导入 Delphi。 我可以从 DLL 创建一个 class 的实例,我可以调用它的方法,一切正常。

我不知道如何注册以接收 DLL 中发生的事件(它从物理设备接收数据)。

I have a C# DLL and a C# test app using that DLL where it is way simpler (it simply adds a handler for that event), but I can't achieve that in Delphi.

我已经编写了自己的小 C# DLL,其中存在事件(与原始 DLL 中的方式相同)。 这是它的代码:

我的 C# DLL:

namespace ClassLibrary3
{
    public class FlowDataEventArgsMine : EventArgs
    {
        public double Flow { get; set; }
    }

    public class Class3
    {
        public string Hello()
        {
            return "Hello World";
        }

        public event EventHandler<FlowDataEventArgsMine> FlowDataReceivedMine;
    }
}

这是如何在 C# 应用程序中使用的:

c = new Class3();

c.FlowDataReceivedMine += new EventHandler<FlowDataEventArgsMine>(OnNewFlowDataReceivedMine);

private void OnNewFlowDataReceivedMine(object sender, FlowDataEventArgsMine e)
{
  // this method is called when the event provides new flow data
}

在 Delphi 中:

CL := TClass3.Create(NiL);
res0 := CL.Hello;  //this works OK, I can call methods from that class

CL.FlowDataReceivedMine := MyMethodToBeCalled;  //this is NOT OK - how can I register for that event? It's not even showing that event as a part of this Class

CL.Free;

显然,我试图阅读我能找到的每一篇文章、问题和帖子。 我有一种感觉,我已经阅读了一半的互联网,但我找不到任何可以为我提供解决方案的东西。

任何人都可以指出一个工作示例,我可以在 Delphi 中实现与 C# 中简单的方法相同的功能(我的意思是,只需添加一个在事件发生时调用的方法)?

编辑:

在我的 Delphi 应用程序中使用 C# Dll 时,真的不可能接收到任何类型的信息吗? During research I encountered some info that exported class from C# DLL needs to implement some interface, and in my Delphi app I should implement the same interface and this would allow me to handle events from that DLL (but didn't found any full solution as示例,而我发现的内容不足以为我提供可行的解决方案)。

这篇文章看起来很有希望,作者说他能够做到这一点,但不幸的是,那里给出的步骤对我不起作用,并且一步一步的博客不再可用:

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

感觉就像在兜圈子,仍然不确定什么是可能的,什么是不可能的:/

I'm by no means a Delphi expert (in that I haven't written a single line of Delphi before) but I was able to find this which explains how to handle a event in Delphi which was raised by C#, basically you need to create a function pointer to a function you want to invoke, and that function must have the exact same parameters as the C# event, something like

procedure MyMethodToBeCalled(ASender: _ClrObject; AEventArgs: _ClrEventArgs); stdcall;
begin
  // Your code
end;

然后通过调用Add[YourEventNameHere]方法来连接它

begin
  MyMethodPointer := MyMethodToBeCalled;

  // add
  CL.AddFlowDataReceivedMine(ni, @MyMethodPointer);

  // remove
  CL.RemoveFlowDataReceivedMine(ni, @MyMethodPointer);
end;

这使用 Delphi 的 .NET 运行时库

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM