温馨提示×

如何在Delphi项目中调用C#编写的DLL

c#
小樊
162
2024-08-19 15:54:33
栏目: 编程语言

要在Delphi项目中调用C#编写的DLL,可以按照以下步骤操作:

  1. 创建一个C#类库项目,并编写需要调用的方法。在方法前面加上 [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);
        }
    }
}
  1. 编译项目,生成 DLL 文件。

  2. 在Delphi项目中引入 System.Runtime.InteropServices 单元。

  3. 使用 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.
  1. 在Delphi中调用C#编写的DLL方法。

0