用DELPHI创建DLL文件,封装窗体的实现方法实例:
即一个程序不再是单一的一个EXE文件了,而是由一个EXE文件加N个DLL文件组成,这样做的原因是方便以后的维护与更新,也是跨平台开发的重要一步。
1, 打开DELPHI,新建一个Dll Wizard
2, 在新建的Dll里新建一个Form
3, 在新建的Form里uses stdctrls
4, 在var下面写:
1 2 | Procedure SynAPP(App:THandle);stdcall; Procedure ShowForm;stdcall; |
(注:如果要让C#调用,则应该注意函数的大小写。)
6,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var Form1: TForm1; Procedure SynAPP(App:THandle);stdcall; Procedure ShowForm;stdcall; implementation {$R *.dfm} Procedure SynAPP(App:THandle);stdcall; Begin Application . Handle:=app; End ; Procedure ShowForm;stdcall; Begin Form1 := Tform1 . create(Application); Form1 . ShowModal; FreeAndNil(Form1); End ; |
一定要注意FreeAndNil(Form1);一定要有。
7, 在dll的Library文件里的{$R *.res}下面写:
1 2 | exports SynAPP,ShowForm; |
上面到此为止完成了DLL封装窗体的创建
下面是调用了
1, 在要调用DLL文件的程序的var下写:
1 2 | Procedure SynAPP(App:THandle);stdcall;external 'my.dll' ; //----你的DLL文件名 Procedure ShowForm;stdcall;external 'my.dll' ; //----你的DLL文件名 |
注:把你写好的DLL放在本程序的同一目录下;
2, 在你的程序的Button的On Click事件下写:
1 2 | SynAPP(applicatiln . Handle); ShowForm; |
在C#中调用就这样写:
先加入引用:using System.Runtime.InteropServices;
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace dllForm { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private const string _fileDll = @"C:\Users\chenming\Desktop\dllForm\dllForm\bin\Debug\dllForm.dll" ; [DllImport(_fileDll, EntryPoint = "SynAPP" , CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern string SynAPP(IntPtr i); [DllImport(_fileDll, EntryPoint = "ShowForm" , CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern string ShowForm(); private void button1_Click( object sender, EventArgs e) { SynAPP( this .Handle); ShowForm(); } } } |
其它注意的地方:
1.C#中的double与Delphi中的double数据类型对应。不能是Delphi中的Extended类型。
2.Delphi中的函数的返回不能为Stirng,改为PChar,参数可以为String。