Delphi 制作 .dll 动态链接库,封装常用的函数。
1,创建 dll 文件:
建立工程 文件 MyDll.dpr:
library Mydll;
uses
SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;
{$R *.RES}
//EXE file Full path:
Function appPath(): Pchar; stdcall;
begin
result := Pchar(extractFilepath(application.ExeName));
end;
/////
procedure myMsg(Const sMsg: Pchar); stdcall;
begin
ShowMessage(sMsg);
end;
////////信息框定义:
function myMsgBox(Prompt,Wincaption:Pchar; btnType:integer): integer; stdcall;
begin
result :=Application.MessageBox(Prompt, Wincaption, btnType);
end;
/////
function myLeftStr(str: Pchar; i: integer): Pchar; stdcall;
begin
result :=Pchar(copy(str,1,i));
end;
/////
function myRightStr(str: Pchar; i: integer): Pchar; stdcall;
begin
result :=Pchar(copy(str,length(str)-i+1,255));
end;
////////////
function mySpaces(n: integer): Pchar; stdcall;
var
i: integer;
s: string;
begin
if n<=0 then
begin
result := Pchar('');
exit;
end;
s := '';
for i := 1 to n do
s := s + ' ';
result := Pchar(s);
end;
exports //函数输出口定义
appPath name 'appPath',
myMsg name 'Msg',
myMsgBox name 'MsgBox',
myLeftStr name 'LeftStr',
myRightStr name 'RightStr',
mySpaces name 'Spaces';
begin
end.
按 Ctrl+F9编译,生成 mydll.dll 文件。
2,调用 dll:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
unction myAppPath():Pchar; stdcall; External 'Mydll.dll' name 'appPath';
function myMsg(s:Pchar):Pchar; stdcall; External 'Mydll.dll' name 'Msg';
function myMsgBox(s1,s2:Pchar; btnType:integer):Pchar; stdcall; External 'Mydll.dll' name 'MsgBox';
function myLeftStr(s:Pchar; n:integer):Pchar; stdcall; External 'Mydll.dll' name 'LeftStr';
function myRightStr(s:Pchar; n:integer):Pchar; stdcall; External 'Mydll.dll' name 'RightStr';
function mySpaces(n: integer):Pchar; stdcall; External 'Mydll.dll' name 'Spaces';
type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
Tmyspc = function(n: integer): Pchar;
var
Form1: TForm1;
implementation
{$R *.dfm}
//静态调用
procedure TForm1.Button1Click(Sender: TObject);
begin
Edit1.Text := myAppPath();
myMsg('test myMsg ...');
myMsgBox('test myMsgBox ...', 'win-caption', 0);
Edit1.Text := myLeftStr('123456789', 3); //123
Edit1.Text := myRightStr('123456789', 3); //789
Edit1.Text := 'AAA' + mySpaces(5) + 'BBB'; //AAA BBB
end;
end.
注意:函数的参数和返回值为 string 类型时,用 pchar 代替。
代码测试环境:
操作系统:Windows Server 2003,Delphi7.0
作者:张庆(网眼) 西安 PHP 教育培训中心 2010-9-3
来自“网眼视界”:http://blog.why100000.com
作者微博:http://t.qq.com/zhangking
“十万个为什么”电脑学习网:http://www.why100000.com