Loading and unloading the Windows process using DLL



// Create a new empty Win32 console mode application project, source file name: testdll.cpp,

// Using moredll.dll that uses Dllmain(). For Windows Xp Pro SP2, you should copy moredll.dll to C:\Windows\Sytem32 folder

// Using Run-Time Dynamic Linking. A simple program that uses LoadLibrary() and GetProcAddress() to access Dllmain() of moredll.dll.

// No function to be exported, just testing...

#include <stdio.h>

#include <windows.h>


typedef void (*MYPROC)(LPTSTR);


int main(void)




BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;


// Get a handle to our DLL module, moredll.dll...this module has been copied to C:\WINDOWS\System32 directory...

hinstLib = LoadLibrary(L"moredll");


// If the handle is valid, try to get the function address.

if (hinstLib != NULL)


printf("The DLL handle is valid...\n");

// The "Anonymfunction" function is fictitious....so the address should be invalid. Verify it through the output, error code 127...

ProcAdd = (MYPROC) GetProcAddress(hinstLib, "Anonymfunction");


// If the function address is valid, call the function.

if (ProcAdd != NULL)


printf("The function address is valid...\n\n");

fRunTimeLinkSuccess = TRUE;

// Ready to execute DLLmain()...



printf("The function address is not valid, error: %d.\n", GetLastError());



printf("\nThe DLL handle is NOT valid, error: %d\n", GetLastError());


// Free the DLL module.

fFreeResult = FreeLibrary(hinstLib);

if (fFreeResult != 0)

printf("FreeLibrary() is OK.\n");


printf("FreeLibrary() is not OK.\n");

return 0;



Output example:


The DLL is loading...from moredll.dll.

CreateFileMapping() is OK.

MapViewOfFile() is OK.

The DLL handle is valid...

The function address is not valid, error: 127.

The DLL is unloading from a process... from moredll.dll.

FreeLibrary() is OK.

Press any key to continue . . .


Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows Xp Pro SP2

Target platform: none, just for learning and fun

Header file: Standard and Windows

Additional library: Windows Platform SDK

Additional project setting: Set project to be compiled as C.

Project->your_project_name Properties->Configuration Properties->C/C++->Advanced->Compiled As: Compiled as C Code (/TC)

Other info: non-CLR or unmanaged. Need to add Advapi32.lib (Advapi32.dll) to the project. Click the Project menu->Select the your_project_name Properties... sub menu->Expand the Configuration Properties folder on the left pane->Expand the Linker subfolder->Select the Input subfolder->Select the Additional Dependencies field on the right pane->Click the ... at the end of the field->Type in 'Advapi32.lib' in the empty pane->Click the OK button->Click the OK button second time to close the project Properties dialog.

To do: Loading and unloading the Windows process using DLL

To show: The Windows DLL program example in Win32 example




C and C++ Programming Resources | C & C++ Code Example Index