要在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.