简体   繁体   English

如何在C ++(Dev C ++编译器)中强制卸载库?

[英]How force unload library in C++ (Dev C++ compiler)?

I saw a Delphi (Object Pascal) code that force unloads any module (dll) that is loaded inside my software. 我看到了一个Delphi(对象Pascal)代码,该代码强制卸载软件中已加载的任何模块(dll)。 Then with base in this code, I'm wanting and needing of something similar now in C++ (Dev C++). 然后,在此代码的基础上,我现在需要C ++(Dev C ++)中的类似功能。

Someone can help me please? 有人可以帮我吗?

Here is Delphi code that I saw: 这是我看到的Delphi代码:

procedure ForceRemove(const ModuleName: string);
var
  hMod: HMODULE;
begin
  hMod := GetModuleHandle(PChar(ModuleName));
  if hMod=0 then 
    exit;
  repeat
  until not FreeLibrary(hMod);
end;

The functions 功能

HMODULE GetModuleHandle(LPCTSTR modulename)
BOOL FreeLibrary(HMODULE)

are functions of the Windows API. 是Windows API的功能。 It can be called from any language that supports programming against the Windows API, as C++ 可以从支持Windows API编程的任何语言(如C ++)中调用

Only recommendation: Remove the loop (the repeat until not ...) in your sample above. 仅建议:删除上面示例中的循环(重复执行,直到没有...)。 It should be replaced by code that interprets the return value of the call to FreeLibrary, documentation here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683152(v=vs.85).aspx 应该用解释对FreeLibrary的调用的返回值的代码代替,这里的文档: https ://msdn.microsoft.com/zh-cn/library/windows/desktop/ms683152( v= vs.85).aspx

The DLL will be unloaded from memory (that is to say, the address space of the executing process), as soon as its per-process reference count goes zero; 一旦DLL的每进程引用计数为零,该DLL将从内存中卸载(即执行进程的地址空间)。 you cannot force unloading a DLL globally by repeatedly executing FreeLibrary() if another process still holds a reference. 如果另一个进程仍然持有引用,则无法通过重复执行FreeLibrary()来强制全局卸载DLL。

EDIT: included a direct translation of OP's sample into a C++ snippet: 编辑:包括将OP的示例直接转换为C ++代码段:

void ForceRemove(LPCTSTR ModuleName)
{
    HMODULE hMod;
    hMod = ::GetModuleHandle(ModuleName);
    if(hMod==0) 
        return;
    /* DISCLAIMER potentially infinite loop
     * not advisable in production code,
     * included by request of the OP to
     * match his original */
    while(::FreeLibrary(hMod));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM