下面是 DLL完整源程序和主叫程序完整源程序。包括以下四个文件:
{---------- DLL 主程序 Project2.DPR ----------} library Project2; uses {$R *.RES} { 下面的语句用于向调用该 DLL的程序提供调用接口 } begin {---------- DLL中的单元 Unit2.PAS ----------} unit Unit2; interface uses type { 该过程向外提供 } implementation {$R *.DFM} procedure DoTest(H: THandle; AConn: TADOConnection; S: string; N: Integer); end. {---------- 调用者 Project1.DPR,很普通的工程文件 ----------} program Project1; uses {$R *.RES} begin {---------- 调用者单元Unit1.PAS ----------} unit Unit1; interface uses type var implementation {$R *.DFM} { 外部声明必须和 DLL中的参数列表一致,否则会运行时错误 } { 调用过程 } end.
Project1.DPR {主叫程序}
Unit1.PAS {主叫程序单元}
Project2.DPR {DLL}
Unit2.PAS {DLL单元}
SysUtils,
Classes,
Unit2 in 'Unit2.pas' {Form1};
exports
DoTest; { 过程来自单元Unit2 }
end.
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, ADODB, StdCtrls, Menus;
TForm1 = class(TForm)
ADOConnection1: TADOConnection;{ 本地数据库连接 }
Memo1: TMemo; { 用于显示信息 }
private
public
end;
procedure DoTest(H: THandle; { 获得调用者的句柄 }
AConn: TADOConnection;{ 获得调用者的数据库连接 }
S: string; { 获得一些文本信息 }
N: Integer); { 获得一些数值信息 }
cdecl; { 指定调用协议 }
begin
Application.Handle := H; { 将过程的句柄赋值为调用者的句柄 }
{ 上面语句的作用在于, DLL的句柄和调用者的句柄相同,在任务栏中就不会 }
{ 各自出现一个任务标题了。 }
with TForm1.Create(Application) do try{ 创建窗体 }
Memo1.Lines.Append('成功调用'); { 显示一行信息 }
ADOConnection1 := AConn; { 获得数据库连接的实例 }
Memo1.Lines.Append(
ADOConnection1.ConnectionString +
' - ' + S + ' - ' + IntToStr(N)); { 根据得到的参数显示另一行信息 }
ShowModal; { 模式化显示窗体 }
finally
Free; { 调用结束时销毁窗口 }
end;
end;
Forms,
Unit1 in 'Unit1.pas' {Form1};
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Db, ADODB;
TForm1 = class(TForm)
Button1: TButton; { 按此按钮进行调用 }
ADOConnection1: TADOConnection; { 本地数据库连接,将传递给 DLL }
procedure Button1Click(Sender: TObject);{ 调用 DLL}
private
public
end;
Form1: TForm1;
procedure DoTest(H: THandle; { 传递句柄 }
AConn: TADOConnection; { 传递数据库连接 }
S: string; { 传递文本信息 }
N: Integer); { 传递数值信息 }
cdecl; { 指定调用协议 }
external 'Project2.dll';{ 指定过程来源 }
procedure TForm1.Button1Click(Sender: TObject);
begin
DoTest(Application.Handle,
ADOConnection1,
'Call OK',
256);
end;
(责任编辑