Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unload DLL from memory in C?

How to unload DLL from memory. I used FreeLibrary but it is still loaded

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

I used UnmapViewOfFile and FreeLibraryAndExitThread but it still in memory too

like image 715
user7435875 Avatar asked Mar 12 '17 14:03

user7435875


1 Answers

In this example, I'll show a short test where we can see that the two functions LoadLibrary and FreeLibrary works very well.

I'll use Process explorer to show if the DLL is loaded or not in the current process address space.

So I have created a very simple dll named test3.dll

And here is a simple program to use it:

// 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;
}

First step:

When we execute this statement:

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

Here is the result:

enter image description here

We can see clearly that test3.dll is loaded in the address space of the process useDLL.exe

Second step:

When executing fFreeResult = FreeLibrary(hinstLib); statement, here is the result:

enter image description here

As we see, the DLL is no longer loaded in the address space of the process useDLL.exe

The two functions LoadLibrary and FreeLibrary works great.

You can look at this tutorial to see how to use process explorer to show the loaded DLL in a given process.

like image 176
HDJEMAI Avatar answered Sep 20 '22 09:09

HDJEMAI