本文主要是介绍DLL的另类调用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
优点:
1.使用静态调用,无动态库时系统完全无法运行
2.速度比动态调用快
unit uTestDLLBase;
interface
uses Windows, Classes, Messages, StdCtrls, SysUtils;
const
cTestDLLName = 'Test.dll';
type
//定义函数类型
TAdd = function (AInt1,AInt2:Integer):Integer; stdcall;
TLev = function (AInt1,AInt2:Integer):Integer; stdcall;
//封装接口类
TTestClass = class
private
public
function _Add(AInt1,AInt2:Integer):Integer;
function _Lev(AInt1,AInt2:Integer):Integer;
end;
var
TestClass:TTestClass = nil;
//加载动态库
function LoadDLL:Boolean;
function DLLLoaded:Boolean;
//卸载动态库
procedure UnLoadDLL;
implementation
var
//动态库句柄
hDLLHandle:THandle = 0;
Add:TAdd;
Lev:TLev;
function LoadDLL:Boolean;
begin
if hDLLHandle = 0 then
hDLLHandle := LoadLibrary(cTestDLLName);
Result := hDLLHandle <> 0;
end;
function DLLLoaded:Boolean;
begin
Result := hDLLHandle <> 0;
end;
type
//定义结构类型
TTestStubRec = record
StubProc:Pointer;
ProcVar:PPointer;
Name:PChar;
end;
function CallStubFunc(AIndex:Integer):Pointer; forward;
procedure Lpfn_Add; asm mov eax, 0; call CallStubFunc; jmp eax; end;
procedure Lpfn_Lev; asm mov eax, 1; call CallStubFunc; jmp eax; end;
const
cEntryCount = 2;
EntryFuncArr : array[0..cEntryCount-1] of TTestStubRec = (
(StubProc:@Lpfn_Add;ProcVar:@@Add;Name:PChar('Add')),
(StubProc:@Lpfn_Lev;ProcVar:@@Lev;Name:PChar('Lev')));
function CallStubFunc(AIndex:Integer):Pointer;
begin
with EntryFuncArr[AIndex] do
begin
Result := GetProcAddress(hDLLHandle,Name);
ProcVar^ := Result;
end;
end;
procedure InitEntryStub;
var
i:Integer;
begin
for i := 0 to cEntryCount-1 do
with EntryFuncArr[i] do
ProcVar^ := StubProc;
end;
procedure UnLoadDLL;
var
hTmpHandle:THandle;
begin
hTmpHandle := InterlockedExchange(Integer(hDLLHandle),0);
if hTmpHandle <> 0 then
begin
FreeLibrary(hTmpHandle);
InitEntryStub;
end;
end;
{ TTestClass }
function TTestClass._Add(AInt1, AInt2: Integer): Integer;
begin
Result := Add(AInt1,AInt2);
end;
function TTestClass._Lev(AInt1, AInt2: Integer): Integer;
begin
Result := Lev(AInt1,AInt2);
end;
initialization
InitEntryStub;
finalization
UnLoadDLL;
end.
这篇关于DLL的另类调用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!