[整理]c#简单调用DELPHI DLL封装窗体
C#调用DELPHI DLL文件。
DELPHI DLL部分代码
Form代码
1
var2
Form1: TForm1;3
procedure SynAPP(App:THandle);stdcall;4
procedure ShowForm;stdcall;5

6
implementation7

8
uses Unit2;9

10
{$R *.dfm}11

12
procedure SynAPP(App:THandle );stdcall;13
begin14
Application.Handle := App;15
end;16

17
procedure ShowForm;stdcall;18
begin19
Form1 := TForm1.Create (Application);20
Form1.ShowModal;21
FreeAndNil(Form1);22
end
Class
1
Function MyString(s:PChar):PChar;stdcall;2
begin3
Result :=s;4
end;5

6
Function MyMax ( X , Y : integer ) : integer ; stdcall ;7
begin8
if X > Y then9
Result := X10
else11
Result := Y ;12
end ;13

14

15

16
{$R *.res}17

18
exports19
MyString ,20
MyMax ,21

22
SynAPP ,23
ShowForm ;
C#代码
1
public partial class HelloWord_Transfer_Delphi_DLL : Form2

{3
public HelloWord_Transfer_Delphi_DLL()4

{5
InitializeComponent();6
}7

8
//定义DLL文件名,此文件路径要加到系统Path中9
private const string _fileDll = @"D:\Demo\Delphi Demo\HelloWord_DLL\HelloWord_DLL.dll";10
//调用非托管Dll,MyMax是ChartAccess.dll公开的函数名称11
[DllImport(_fileDll, EntryPoint = "MyMax", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]12
//C#中的申明13
public static extern int MyMax(int i,int j);14

15

16
[DllImport(_fileDll, EntryPoint = "MyString", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]17
public static extern string MyString(string s);18

19
[DllImport(_fileDll, EntryPoint = "SynAPP", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]20
public static extern string SynAPP(IntPtr i);21

22
[DllImport(_fileDll, EntryPoint = "ShowForm", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]23
public static extern string ShowForm();24

25

26
private void button1_Click(object sender, EventArgs e)27

{28
MessageBox.Show(MyMax(10, 100).ToString());29
}30

31
private void button2_Click(object sender, EventArgs e)32

{33
MessageBox.Show(MyString("aaaaad"));34
}35

36
private void button3_Click(object sender, EventArgs e)37

{38
SynAPP(this.Handle);39
ShowForm();40
}41
}

浙公网安备 33010602011771号