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

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