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

   2024-10-01 9780
核心提示:要在Delphi项目中调用C#编写的DLL,可以按照以下步骤操作:创建一个C#类库项目,并编写需要调用的方法。在方法前面加上 [DllImpo

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

创建一个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);        }    }}

编译项目,生成 DLL 文件。

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

使用 external 关键字在Delphi中声明需要调用的方法。

unit MainUnit;interfaceuses  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.
在Delphi中调用C#编写的DLL方法。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号