windows - 通过 GetModuleHandle/LoadLibrary 和使用 FreeLibrary 加载 DLL

标签 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?或者它的引用计数会在我的应用程序终止时自动递减?

最佳答案

我会引用 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).

所以基本上您不需要调用 FreeLibrary 但您应该考虑这样做。我个人认为当资源没有被正确处理时,这是一个错误。

关于windows - 通过 GetModuleHandle/LoadLibrary 和使用 FreeLibrary 加载 DLL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7364846/

相关文章:

c# - 过滤fiddler以仅捕获特定域的请求

windows - Minifilter 驱动程序、内存映射和记事本

c++ - 控制台应用程序比 GUI 应用程序运行得更快吗?

c++ - 消息处理程序 INT_PTR 返回值的目的是什么?

c++ - 如何将应用程序作为新创建的资源管理器进程的子进程启动?

windows - 将文件内容从内核模式传递到用户模式的最快方法?

windows - UWP : Cannot install appx or appxbundle package

C++ 和 DirectShow

python - 如何使用 Python ctypes 表示打包的 Delphi 记录?

delphi - 如何解决 Delphi 2010 : "[DCC Error] E2223 $DENYPACKAGEUNIT ' OleAuto' cannot be put into a package"? 中的此错误