1. Technology

Controling DLL loading

By

When you are writing dynamic link libraries and need to control the loading and unloading of a DLL, or if you want to initialize your DLL when it is loaded, you can have a function called DllMain do your initialization. Windows calls the DllMain function of a DLL in four instances:

1) When a process attaches the DLL
2) When a thread attaches the DLL
3) When a process detaches the DLL
4) When a thread detaches the DLL

Each DLL has an enty point. This entry point is implemented as a callback function. It is called by system when a set of event occurs. Function has default name DllMain. A DLL that doesn't want to be loaded by a certain caller can simply return False in its DllMain() function once it detects who's calling.

In Delphi, DLLProc is used to specify a procedure that is invoked every time a DLL's entry point is called. A procedure assigned to DLLProc takes one Integer parameter (Reason).

The GetModuleFileName() API function returns the name of the caller module if you pass 0 as its first argument. Such a parameter is the handle of the module whose name you want to know.

When the Reason parameter is DLL_PROCESS_ATTACH, setting ExitCode to a nonzero value causes the entry point to return false.

Here's a sample code, we are allowing only MyCallingApp.exe to load the library (note: the DLL in this example has NO code except the DLLMain procedure):

~~~~~~~~~~~~~~~~~~~~~~~~~
library OnlyMyDLL;

uses
   SysUtils, Windows;

procedure DllMain(reason: integer) ;
var
  buf : array[0..MAX_PATH] of char;
  loader : string;
begin
   case reason of
     DLL_PROCESS_ATTACH:
     begin
       GetModuleFileName(0, buf, SizeOf(buf)) ;
       loader := buf;
       if Pos('MyCallingApp.exe', loader) > 0 then
         ExitCode := -1
     end;
     DLL_PROCESS_DETACH
     begin
       //DLL unloading...
     end;
   end;
end; (*DllMain*)

begin
   DllProc := @DllMain;
   DllProc(DLL_PROCESS_ATTACH) ;


   //more DLL code here...
end.
~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Grayscaling a bitmap
« How to get the current line and column from a Memo

©2014 About.com. All rights reserved.