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;
ShowMessage(sMsg);
////////資訊框定義:
function myMsgBox(Prompt,Wincaption:Pchar; btnType:integer): integer; stdcall;
result :=Application.MessageBox(Prompt, Wincaption, btnType);
function myLeftStr(str: Pchar; i: integer): Pchar; stdcall;
result :=Pchar(copy(str,1,i));
function myRightStr(str: Pchar; i: integer): Pchar; stdcall;
result :=Pchar(copy(str,length(str)-i+1,255));
////////////
function mySpaces(n: integer): Pchar; stdcall;
var
i: integer;
s: string;
if n<=0 then
begin
result := Pchar('');
exit;
end;
s := '';
for i := 1 to n do
s := s + ' ';
result := Pchar(s);
exports //函數輸出口定義
appPath name 'appPath',
myMsg name 'Msg',
myMsgBox name 'MsgBox',
myLeftStr name 'LeftStr',
myRightStr name 'RightStr',
mySpaces name 'Spaces';
end.
按 Ctrl+F9編譯,生成 mydll.dll 檔案。
2,調用 dll:
unit Unit1;
interface
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 }
Tmyspc = function(n: integer): Pchar;
Form1: TForm1;
implementation
{$R *.dfm}
//靜态調用
procedure TForm1.Button1Click(Sender: TObject);
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
注意:函數的參數和傳回值為 string 類型時,用 pchar 代替。
代碼測試環境:
作業系統:Windows Server 2003,Delphi7.0
作者:張慶(網眼) 西安 PHP 教育教育訓練中心 2010-9-3
本文轉自網眼51CTO部落格,原文連結:http://blog.51cto.com/itwatch/397391,如需轉載請自行聯系原作者