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.

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值