Click here to Skip to main content
16,017,899 members
Articles / Programming Languages / C++
Article

Create Simple Load time DLLs

Rate me:
Please Sign up or sign in to vote.
4.26/5 (30 votes)
7 Dec 2003CPOL5 min read 231.3K   9.7K   62   29
This article explains how to create simple Load time DLL in Microsoft Foundation Class and Win32 API

Introduction

If you like to create modular software, you choose DLLs. Dynamic linked libraries are easy to create compared to applications. Dynamic linked library is a set of modules that contains a set of functions or other called DLLs.

In windows operating system some of the DLLs are important. They are the following - User32.dll manages user interface related tasks. The Gdi32.dll manages graphic device interface related (GDI) tasks. In DOS world, programs write directly into video memory. But, in windows layer called Graphic Device Interface (GDI) exists. The advapi32.dll manages registry related tasks. The comdlg32.dll manages the common dialog box related tasks (Example File open dialog box, file save and save as dialog box). The comctrl32.dll manages the windows common control related tasks.

The Windows DLLs are the backbone of windows operating system. The windows operating system manages the large set of system DLLs. When the windows operating system starts, the DLLs load to system memory.

Types of DLL

The windows operating system has two types of DLLs. There are the following.

  1. Load Time Dynamic Linking
  2. Run Time Dynamic Linking

The Load Time Dynamic Linking load the DLLs at the load time. When the application starts, all the required DLLs are loaded into memory in the startup time. In this method the system tries to find the DLLs in the following locations.

  1. The Windows System Directory
  2. The Windows directory
  3. The Application local path
  4. The directories listed in the path environment variables

Load Time DLLs requires LIB file and declaration file (.h), when we create application programs. We insert the header file in the application and link with the LIB file in the application project settings. The DLLs do not handle windows messages. The DLLs are simply set of functions or variables declared in the declaration file ( .h) and implemented in the implementation file(.cpp).

The run time dynamic linking tries to load DLL at run time. The LoadLibrary function is used to load a DLL at run time. The syntax for LoadLibrary is the following.

HINSTANCE hinst = LoadLibrary(LPCTSTR dllfilename);

If the LoadLibrary returns success, then we use GetProcAddress get the address of the functions. After calling DLL function we call FreeLibrary to free the DLL library. In this run time dynamic linking, we do not load all the DLL files in the startup time. Whenever we want to load, we load and unload the DLLs.

Create Load time Win32 DLL

We already saw, that using DLLs is easy to create modular applications. In win32 Dynamic linked library project choose DLL and add support for some export symbols in second step. In that class declaration add your method and return types. When you allocate memory in the DLL file, you also deallocate it. If you deallocated from the client (like from application) it may be deallocated but we cannot be sure.

__declspec(dllimport) tells the compiler to add some symbols for import from the DLLs. This way the __declspec(dllexport) tells the compiler to export some symbols. In our sample program declare the three functions. The functions are to add, multiply and subtract the two values. These simple DLLs help you understand the basic DLLs functionality.

The DLL entry point is the DllMain; the DllMain has the following syntax.

BOOL APIENTRY DllMain(HANDLE hModule,
                      DWORD  ul_reason_for_call,
                      LPVOID lpReserved)
{
    switch( ul_reason_for_call ) {
    case DLL_PROCESS_ATTACH:
    .
    .
    case DLL_THREAD_ATTACH:
    .
    .
    case DLL_THREAD_DETACH:
    .
    .
    case DLL_PROCESS_DETACH:
    .
    .
    }
    return TRUE;
}

You copy DLL file into system directory and copy LIB file into Visual C++ Lib directory and link to lib file. In application module make sure to implement the header file. In our example file is declared in the following manner.

#ifdef WIN32DLL_EXPORTS
#define WIN32DLL_API __declspec(dllexport)
#else
#define WIN32DLL_API __declspec(dllimport)
#endif

// This class is exported from the Win32DLL.dll
class WIN32DLL_API CWin32DLL {
public:
    CWin32DLL(void);
    // TODO: add your methods here.
    int add(int a,int b);
    int sub(int a,int b);
    int mul(int a,int b);
};
extern WIN32DLL_API int nWin32DLL;

The class CWin32DLL has been declared as __declspec(dllexport) using WIN32DLL_API. So, all the class member functions and member variables are __declspec(dllexport). All the member functions are declared as public.

In our implementation file, we link and call the functions.

The run time dynamic linking in the client program are the following.
#include "stdio.h"
#include "windows.h"

typedef VOID (*MYPROC)(LPTSTR);

VOID main(VOID)
{
    HINSTANCE hinstLib;
    MYPROC ProcAdd;
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

    // Get a handle to the DLL module.

    hinstLib = LoadLibrary("win32dll.dll");

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

    if (hinstLib != NULL)
    {
        ProcAdd = (MYPROC) GetProcAddress(hinstLib, "add");

    // Do add operation

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

        if (fRunTimeLinkSuccess = (ProcAdd != NULL))
            (ProcAdd) ("message via DLL function\n");

        // Free the DLL module.

        fFreeResult = FreeLibrary(hinstLib);
    }

    // If unable to call the DLL function, use an alternative.

    if (! fRunTimeLinkSuccess)
        printf("message via alternative method\n");
}

Create MFC DLL

Microsoft Foundation Class (MFC) library can be used to create simplified DLLs. The MFC supports two types of DLLs. Those are the following.

  1. Regular DLL with MFC statically linked
  2. Regular DLL using shared MFC Dll
  3. MFC Extension DLL ( Using shared MFC DLL)

In the regular DLL with MFC statically linked, the Client may be MFC based application or Non-MFC application. Our sample program application is based on a DLL using shared MFC dll.

MFC Extension DLL has reusable classes derived from existing Microsoft foundation Classes. Extension DLL is built from Dynamic linked library version of the DLL. In MFC, regular DLLs are initialized in three ways. The DLL has a CWinApp Object. MFC OLE initializes using MFC global AfxOleInitModule function. The MFC Database initializes into MFC using global AfxDbInitModule function. MFC Sockets are initialized using AfxNetInitModule function.

Initializing the Extension DLLs is as following.

extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID 
lpReserved)
{
   if (dwReason == DLL_PROCESS_ATTACH)
   {
      // test.dll Initializing!
      // Extension DLL one-time initialization

      AfxInitExtensionModule(PROJNAMEDLL, hInstance);

      // Insert this DLL into the resource chain
      new CDynLinkLibrary(dll);

   }
   else if (dwReason == DLL_PROCESS_DETACH)
   {
      // test.dll Terminating!
   }
   return 1;   // ok
}

In our example, The Dll has DrawEllipse function. We pass the CRect structure and CDC to DLL. The DLL function draws the DLL with selected Blue Brush.

Benefits of DLLs

The benefits of using DLLs are the following.

  1. The Dynamic linked library shares the memory. So, the system performance is improving compared to using applications.
  2. We can build and test separately each DLL.
  3. We can create DLLs for different languages. Windows use C DLL, C++ DLL, Fortran DLL and PASCAL DLL etc. Even windows support some version of Smalltalk DLLs.
  4. We can load and unload at run time. This helps to improve application performance.
  5. The big software products were divided into several DLLs. The developers easily develop their application.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Selvam has worked on several technologies like Java, Python, Big data, VC++, MFC, Windows API and Weblogic server. He takes a lot of interest in reading technical articles and enjoys writing them too. He has been awarded as a Microsoft Community Star in 2004, MVP in 2005-06, SCJP 5.0 in 2009, Microsoft Community Contributor(MCC) 2011.

Big Data
o Google Professional Data Engineer 2021
o Confluent Certified Developer for Apache Kafka 2020
o Datastax Apache Cassandra 3.x Developer Associate Certification 2020
✓ Cloud
o Google Professional Cloud Architect 2021
o Microsoft Certified: Azure Solutions Architect Expert 2020
o AWS Certified Solutions Architect - Associate 2020
✓ Oracle Certified Master, Java EE 6 Enterprise Architect (OCMEA) 2018

Github : https://github.com/selvamselvam
Web site: http://www.careerdrill.com
Linkedin: https://www.linkedin.com/in/selvamselvam/

Comments and Discussions

 
Questionimport and export Pin
bkelly1320-Feb-16 14:16
bkelly1320-Feb-16 14:16 
QuestionPlease Build Step-BY-Step project to use open source DLL in VC++ 2010 MFC Application Pin
Sumit Makhe8-Mar-12 21:25
Sumit Makhe8-Mar-12 21:25 
AnswerRe: Please Build Step-BY-Step project to use open source DLL in VC++ 2010 MFC Application Pin
Selvam R9-Mar-12 3:24
professionalSelvam R9-Mar-12 3:24 
GeneralMy vote of 5 Pin
Aburawan12-Jul-10 21:32
Aburawan12-Jul-10 21:32 
GeneralC# DllImport, calling the function causes EntryPointNotFoundException Pin
Annedore Söchting18-Jun-10 2:15
Annedore Söchting18-Jun-10 2:15 
QuestionHow to call Dll with Dll? Pin
imclare26-Jan-10 22:22
imclare26-Jan-10 22:22 
Generalerror:WIN32DLL_API class CWin32DLL { Pin
slkpovud4-Dec-07 23:14
slkpovud4-Dec-07 23:14 
QuestionHow Create Load time DLLs on .net Pin
va250516-Feb-07 7:50
va250516-Feb-07 7:50 
AnswerRe: How Create Load time DLLs on .net Pin
Portatofe2-Oct-08 5:56
Portatofe2-Oct-08 5:56 
AnswerRe: How Create Load time DLLs on .net Pin
Selvam R8-Sep-09 0:29
professionalSelvam R8-Sep-09 0:29 
GeneralStatic .lib Help Pin
ArunAntony17-Mar-06 20:24
ArunAntony17-Mar-06 20:24 
Questionwrong run time dynamic linking example? Pin
AlenkaZajka22-Jun-05 23:46
AlenkaZajka22-Jun-05 23:46 
GeneralCannot find the procedure in the DLL Pin
CalicoSkies4-Apr-05 18:17
CalicoSkies4-Apr-05 18:17 
Hi -

I have created a DLL as you describe (but using Visual Studio's DLL project wizard - it sets up a DLL to look just like you describe). In my application, where I want to use the DLL, I have used a typedef and LoadLibrary and GetProcAddress as you describe, to get access to a function in the DLL. I have also linked with my DLL's .lib file. However, when I run my application, it can't find the function name in the DLL. Is there a common mistake that I might be doing?

Eric
GeneralRe: Cannot find the procedure in the DLL Pin
Selvam R4-Apr-05 19:09
professionalSelvam R4-Apr-05 19:09 
GeneralRe: Cannot find the procedure in the DLL Pin
Frank K1-Nov-05 5:20
Frank K1-Nov-05 5:20 
GeneralDLL export for template base classes Pin
Jafar amiri3-Oct-04 0:55
Jafar amiri3-Oct-04 0:55 
GeneralRe: DLL export for template base classes Pin
Selvam R4-Apr-05 19:05
professionalSelvam R4-Apr-05 19:05 
QuestionHow to link implicitly a foreign DLL Pin
CEERI1-Oct-04 0:10
CEERI1-Oct-04 0:10 
AnswerRe: How to link implicitly a foreign DLL Pin
Anonymous1-Oct-04 4:02
Anonymous1-Oct-04 4:02 
QuestionHow to export functions Pin
Michael Olsen17-Mar-04 23:40
Michael Olsen17-Mar-04 23:40 
AnswerRe: How to export functions Pin
BlackDice23-Mar-04 3:18
BlackDice23-Mar-04 3:18 
GeneralIn MFC Which DLL use Pin
Selvam R15-Dec-03 18:32
professionalSelvam R15-Dec-03 18:32 
Questiondlls,lib,headers??? Pin
Member 30598315-Dec-03 17:55
Member 30598315-Dec-03 17:55 
AnswerRe: dlls,lib,headers??? Pin
Selvam R16-Dec-03 5:46
professionalSelvam R16-Dec-03 5:46 
GeneralPros and Cons Pin
Mike Wild9-Dec-03 22:27
Mike Wild9-Dec-03 22:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.