C# 調用Delphi 動態鏈接庫通過回調實現發佈訂閱

在C#中是通過 委託來實現發佈訂閱機制,其實這和Delphi 中的方法指針類型如出一轍,這裏通過一個小Deamo 來說明一下

  • Delphi 實現動態庫
library mydll;


uses
  SysUtils,
  Dialogs,
  Classes,
  Unit1 in 'Unit1.pas' {Form1};

{$R *.res}
function showInfo(const s:PAnsiChar):Integer;stdcall;
begin
  showMessage('這是Delphi 方法,收到的參數是:'+s);
  result:=1;
end;
exports
  showInfo,showfrm;
begin
end.

Form1 窗體部分代碼:
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ExtCtrls, StdCtrls;

type
  TMyMethod=procedure(const s:PAnsiChar);stdcall; //這裏其實和C#中的委託是一致的
  TForm1 = class(TForm)
    tmr1: TTimer;
    mmo1: TMemo;
    btn1: TButton;
    procedure tmr1Timer(Sender: TObject);
    procedure btn1Click(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    FMyMethod:TMyMethod;
  public
    { Public declarations }
    property OnMyMethod:TMyMethod read FMyMethod write FMyMethod;
  end;

var
  Form1: TForm1;
procedure showfrm(const handle:Cardinal;method1:TMyMethod);stdcall;
implementation

{$R *.dfm}
procedure showfrm(const handle:Cardinal;method1:TMyMethod);stdcall;
begin
  Application.Handle:=handle;
  if not Assigned(Form1) then
  begin
    form1:=TForm1.Create(Application);
    Form1.OnMyMethod:=method1;
    Form1.tmr1.Enabled:=True;
  end;
  Form1.OnMyMethod:=method1;
  Form1.Show;
end;
procedure TForm1.tmr1Timer(Sender: TObject);
begin
  if Assigned(OnMyMethod) then
  begin
    OnMyMethod(PAnsiChar('這是Delphi 的回調,時間:'+datetimetostr(now)));
  end;

end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  tmr1.Enabled:=True;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Form1.Free;
  Form1:=nil;
end;

end.


  • C# 部分代碼
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace WinOtherDll
{

    public delegate void MyMehtod(string s);
    public partial class Form1 : Form
    {

        [DllImport("mydll.dll",CharSet =CharSet.Ansi)]
        public static extern Int32 showInfo(string s);
        [DllImport("mydll.dll", CharSet = CharSet.Ansi)]
        public static extern void showfrm(IntPtr h,MyMehtod myMehtod);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int a=showInfo("我是C#");
            MessageBox.Show($"返回結果是:{a}");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            showfrm(this.Handle,(s)=> {
                listBox1.Items.Add(s);
            });
        }

        private void button3_Click(object sender, EventArgs e)
        {
            showfrm(Handle, null);
        }
    }
}

  • 效果:
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章