delphi編寫DLL安全
下面在delphi中編寫一個簡單的dll,在該dll中只有一個max函數,返回2個數中的大數(Delphi 5.0)函數
一、New->DLL;取名爲DLL_0001,編寫代碼:spa
library dll_0001;orm
uses
SysUtils,
Classes;it
{$R *.RES}io
function max(x,y:integer):integer;stdcall;
begin
if(x>y) then
max :=x
else
max :=y;
end;function
exports max;class
begin搜索
end.程序
紅色部分爲本身編寫,這裏和普通的delphi函數是同樣的,只是在返回值中帶個stdcall參數,而後用exports把函數導出
================================================================================
調用dll分動態調用和靜態調用2中,動態調用寫起來簡單,安全點,動態調用複雜不少,但很靈活;
如今編寫一個程序,來調用上面寫的dll_0001.dll文件中的max函數
1、new一個Application,在Form中放入2個TEdit、1個TLabek;
2、
一、靜態調用
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
procedure Edit2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
function max(x,y:integer):integer;stdcall;
external 'dll_0001.dll';
procedure TForm1.Edit2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key =vk_return then
label1.Caption :=IntToStr(max(StrToInt(Edit1.text),StrToInt(edit2.text)));
end;
end.
紅色代碼本身添加,其中external "dll_name"中的dll_name能夠是dll的絕對路徑,要是該dll文件在你的搜索路徑中,能夠直接寫文件名,可是.dll不能少寫
二、動態調用,代碼以下;
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
procedure Edit2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Edit2KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
type
TFunc =function(x,y:integer):integer;stdcall;
var
Th:Thandle;
Tf:TFunc;
Tp:TFarProc;
begin
if key =vk_return then
begin
Th :=LoadLibrary('dll_0001.dll'); {load dll}
if(Th >0) then
try
Tp :=GetProcAddress(Th,PChar('max'));
if(Tp <>nil) then
begin { begin 1}
Tf :=TFunc(Tp);
Label1.Caption :=IntToStr(
Tf(StrToInt(Edit1.text),StrToInt(Edit2.text)));
end { end 1}
else
ShowMessage('function max not found.');
finally
FreeLibrary(Th);
end
else
ShowMessage('dll_0001.dll not exsit.');
end;
end;
end.