windows 通过 GetModuleHandle/LoadLibrary 加载 DLL 并使用 FreeLibrary
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7364846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading DLL via GetModuleHandle/LoadLibrary and using FreeLibrary
提问by kobik
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?
如果使用 LoadLibrary,我们需要调用 FreeLibrary 吗?或者它的引用计数会在我的应用程序终止时自动递减?
回答by mkaes
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).
系统在所有加载的模块上维护每个进程的引用计数。调用 LoadLibrary 会增加引用计数。调用 FreeLibrary 或 FreeLibraryAndExitThread 函数会减少引用计数。当引用计数达到零或进程终止时(无论引用计数如何),系统将卸载模块。
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.
所以基本上你不需要打电话,FreeLibrary
但你应该考虑这样做。我个人认为这是资源处理不当的错误。