要在Delphi項目中調用C#編寫的DLL,可以按照以下步驟操作:
[DllImport("kernel32.dll")]
標簽,以便在Delphi中調用。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);
}
}
}
編譯項目,生成 DLL 文件。
在Delphi項目中引入 System.Runtime.InteropServices
單元。
使用 external
關鍵字在Delphi中聲明需要調用的方法。
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.