如何在Delphi項(xiàng)目中調(diào)用C#編寫(xiě)的DLL

c#
小樊
163
2024-08-19 15:54:33

要在Delphi項(xiàng)目中調(diào)用C#編寫(xiě)的DLL,可以按照以下步驟操作:

  1. 創(chuàng)建一個(gè)C#類庫(kù)項(xiàng)目,并編寫(xiě)需要調(diào)用的方法。在方法前面加上 [DllImport("kernel32.dll")] 標(biāo)簽,以便在Delphi中調(diào)用。
using System;
using System.Runtime.InteropServices;

namespace MyCSharpLibrary
{
    public class MyCSharpClass
    {
        [DllImport("kernel32.dll")]
        public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);

        public void ShowMessageBox()
        {
            MessageBox(IntPtr.Zero, "Hello from C#!", "Message", 0);
        }
    }
}
  1. 編譯項(xiàng)目,生成 DLL 文件。

  2. 在Delphi項(xiàng)目中引入 System.Runtime.InteropServices 單元。

  3. 使用 external 關(guān)鍵字在Delphi中聲明需要調(diào)用的方法。

unit MainUnit;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, StdCtrls, System.Runtime.InteropServices;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

procedure ShowMessageBox; external 'MyCSharpLibrary.dll';

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessageBox;
end;

end.
  1. 在Delphi中調(diào)用C#編寫(xiě)的DLL方法。

0