簡體   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