【问题标题】:How to Unload DLL from memory in C?如何在 C 中从内存中卸载 DLL?
【发布时间】:2017-08-02 13:50:55
【问题描述】:

如何从内存中卸载 DLL。我使用了 FreeLibrary,但它仍在加载中

HINSTANCE hGetProcIDDLL = LoadLibrary("path.dll");
f_funci func = (f_funci)GetProcAddress(hGetProcIDDLL, "method");
int x = func();
FreeLibrary(hGetProcIDDLL);

我使用了UnmapViewOfFileFreeLibraryAndExitThread,但它仍然在内存中

【问题讨论】:

  • FreeLibrary() 返回什么? (您可能还想检查LoadLibrary()GetProcAddress() 的返回值)。
  • @Danny_ds FreeLibrary() 返回 true。
  • 您能解释一下“仍在记忆中”是什么意思吗?
  • 也许你可以尝试调用GetLastError函数,看看它返回了什么。
  • 为什么你认为它还在记忆中?

标签: c winapi memory dll loadlibrary


【解决方案1】:

在这个例子中,我将展示一个简短的测试,我们可以看到LoadLibraryFreeLibrary 这两个函数运行良好。

我将使用Process explorer 来显示 DLL 是否已加载到当前进程地址空间中。

所以我创建了一个名为 test3.dll 的非常简单的 dll

这是一个使用它的简单程序:

// A simple program that uses LoadLibrary and 
// Access test3.dll. 
// Then Unload test3.dll 
#include <windows.h> 
#include <iostream> 

typedef int (__cdecl *MYPROC)(LPWSTR); 

int main( void ) 
{ 
   HINSTANCE hinstLib; 
   BOOL fFreeResult; 

   // Get a handle to the DLL module.
   hinstLib = LoadLibrary(TEXT("test3.dll"));    //1: load the DLL

   // If the handle is valid, unload the DLL
   if (hinstLib != NULL) 
   {  
       fFreeResult = FreeLibrary(hinstLib);      //2: unload the DLL
   } 

   return 0;
}

第一步:

当我们执行这条语句时:

hinstLib = LoadLibrary(TEXT("test3.dll"));

结果如下:

我们可以清楚的看到test3.dll加载在进程useDLL.exe的地址空间中

第二步:

执行fFreeResult = FreeLibrary(hinstLib);语句时,结果如下:

如我们所见,DLL不再加载到进程useDLL.exe的地址空间中

LoadLibraryFreeLibrary 这两个函数效果很好。

您可以查看this tutorial to see how to use process explorer 以显示给定进程中加载​​的DLL。

【讨论】:

  • @user7435875 如果该答案有帮助,您应该接受它。 (因为这是唯一的答案并且恕我直言很有价值,我会推荐它。)
猜你喜欢
  • 1970-01-01
  • 2018-04-06
  • 2021-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多