kobik
kobik

Reputation: 21252

Loading DLL via GetModuleHandle/LoadLibrary and using FreeLibrary

here is my code:

function GetProcedureAddress(var P: FARPROC; const ModuleName, ProcName: AnsiString): Boolean;
var
  ModuleHandle: HMODULE;
begin
  Result := False;
  ModuleHandle := GetModuleHandle(PAnsiChar(AnsiString(ModuleName)));
  if ModuleHandle = 0 then
    ModuleHandle := LoadLibrary(PAnsiChar(ModuleName)); // DO WE NEED TO CALL  FreeLibrary ?
  if ModuleHandle <> 0 then
  begin
    P := Pointer(GetProcAddress(ModuleHandle, PAnsiChar(ProcName)));
    if Assigned(P) then
      Result := True;
  end;
end;

function PathMakeSystemFolder(Path: AnsiString): Boolean;
var
  _PathMakeSystemFolderA: function(pszPath: PAnsiChar): BOOL; stdcall;
begin
  Result := False;
  if GetProcedureAddress(@_PathMakeSystemFolderA, 'shlwapi.dll', 'PathMakeSystemFolderA') then
    Result := _PathMakeSystemFolderA(PChar(Path));
end;

DO we need to call FreeLibrary if using LoadLibrary? or it's reference count will decremented automatically when my application terminates?

Upvotes: 3

Views: 6493

Answers (1)

mkaes
mkaes

Reputation: 14119

I will quote from here.

The system maintains a per-process reference count on all loaded modules. Calling LoadLibrary increments the reference count. Calling the FreeLibrary or FreeLibraryAndExitThread function decrements the reference count. The system unloads a module when its reference count reaches zero or when the process terminates (regardless of the reference count).

So basically you don't need to call FreeLibrary but you should think about doing so. I personally think it is a bug when resources are not handled correctly.

Upvotes: 6

Related Questions