How to Unload DLL from memory in C?

19,143

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.

Share:
19,143
Admin
Author by

Admin

Updated on June 26, 2022

Comments

  • Admin
    Admin almost 2 years

    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

  • Scheff's Cat
    Scheff's Cat over 5 years
    @user7435875 If that answer was helpful you should've accepted it. (As this is the only answer and IMHO valuable, I would recommend it.)