通过GetModuleHandle / LoadLibrary加载DLL并使用FreeLibrary

时间:2011-09-09 16:41:45

标签: windows delphi winapi api

这是我的代码:

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;

如果使用LoadLibrary,我们是否需要调用FreeLibrary?或者当我的申请终止时,它的引用计数会自动递减吗?

1 个答案:

答案 0 :(得分:6)

我将引用here

  

系统维护所有已加载模块的每进程引用计数。调用LoadLibrary会增加引用计数。调用FreeLibrary或FreeLibraryAndExitThread函数会减少引用计数。系统在其引用计数达到零或进程终止时卸载模块(无论引用计数如何)。

所以基本上你不需要拨打FreeLibrary,但你应该考虑这样做。我个人认为资源处理不当是一个错误。