Как я могу сказать, как моя DLL была загружена? - PullRequest
1 голос
/ 06 сентября 2011

Как моя DLL может определить, была ли она загружена неявно или явно?

Пример MyTestDll.dll

library MyTestDll;

uses SimpleShareMem, Windows, Dialogs;

procedure DetectMethodDllLoad: bool;
begin
  // ?????
  // need to detect loading method - implicit or explicit
end;

procedure MyTest; stdcall;
begin
  if DetectMethodDllLoad then
    ShowMessage('Working Program1 (implicit dll load)')
  else
    ShowMessage('Working Program2 (explicit dll load)');
end;

exports MyTest;

begin
end.

Program1.exe (неявная dllзагрузка)

procedure MyTest; stdcall; external 'MyTestDll.dll' Name 'MyTest';

procedure TForm1.Button1Click(Sender: TObject);
begin
  MyTest;
end;

Program2.exe (явная загрузка DLL)

type
  TMyTest = procedure; stdcall;

procedure TForm1.Button1Click(Sender: TObject);
var
  MyTest: TMyTest;
  H: HModule;
begin
  H := LoadLibrary('MyTestDll.dll');
  if H = 0 then
    exit;
  @MyTest := GetProcAddress(H, 'MyTest');
  if Assigned(MyTest) then
    MyTest;
  FreeLibrary(H);
end;

Как реализовать DetectMethodDllLoad?

Ответы [ 3 ]

3 голосов
/ 07 сентября 2011

Если вы можете создать процедуру DllMain, параметр lpReserved для вызова DLL_PROCESS_ATTACH сообщит вам, является ли загрузка статической или динамической.C. Я не знаю, возможно ли это в Delphi.

1 голос
/ 06 сентября 2011

Вот очень хороший учебник с двумя методами, статическим и динамическим:

Статическая и динамическая загрузка библиотеки динамических ссылок - сравнение

0 голосов
/ 07 сентября 2011

Спасибо Гарри Джонстон !!! :)

library MyTestDll;  

uses SimpleShareMem, Windows, Dialogs;  

type
PDllEntryPointFrame = ^TDllEntryPointFrame;
TDllEntryPointFrame = packed record
hModule: THandle; // DLL module handle
dwReason: DWord; // reason for calling DLLEntryPoint function of DLL
bStatic: LongBool; // TRUE if DLL is loading/unloading satically, FALSE - dinamically
end;

function DetectMethodDllLoad: bool;  
asm
mov edx, [hInstance]
mov eax, ebp
@@nextframe:
cmp [eax + $08].TDllEntryPointFrame.hModule, edx
je @@found
mov eax, [eax]
jmp @@nextframe
@@found:
mov eax, [eax + $08].TDllEntryPointFrame.bStatic
end;

procedure MyTest; stdcall;  
begin  
...
end;  

exports MyTest;  

begin  
  if DetectMethodDllLoad then  
    ShowMessage('Working Program1 (implicit dll load)')  
  else  
    ShowMessage('Working Program2 (explicit dll load)');  
end.  

P.s. System.TDLLProcEx не работает в Delphi XE!

library MyTestDll; 

....

procedure MyDLLProcEx(Reason:integer;x:pointer);
begin
if x=nil then showmessage('dyn') else showmessage('stat');
end;

begin
DLLProcEx:=@MyDLLProcEx;
end;

x = ноль всегда: (

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...