Click here to Skip to main content
Click here to Skip to main content
Go to top

Create Simple Load time DLLs

, 7 Dec 2003
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

R.selvam
Software Developer (Senior)
India India
Selvam has worked on several technologies like Core Java, VC++, MFC, Windows API and Weblogic server. He takes a lot of interest in reading technical articles and enjoy 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.
 
Github : https://github.com/selvamselvam
Web site: http://www15.brinkster.com/selvamselvam
Follow on   LinkedIn

Comments and Discussions

 
QuestionPlease Build Step-BY-Step project to use open source DLL in VC++ 2010 MFC Application PinmemberSumit Makhe8-Mar-12 21:25 
AnswerRe: Please Build Step-BY-Step project to use open source DLL in VC++ 2010 MFC Application PinmemberR.selvam9-Mar-12 3:24 
GeneralMy vote of 5 PinmemberAburawan12-Jul-10 21:32 
GeneralC# DllImport, calling the function causes EntryPointNotFoundException PinmemberAnnedore Rößling18-Jun-10 2:15 
QuestionHow to call Dll with Dll? Pinmemberimclare26-Jan-10 22:22 
Generalerror:WIN32DLL_API class CWin32DLL { Pinmemberslkpovud4-Dec-07 23:14 
QuestionHow Create Load time DLLs on .net Pinmemberva250516-Feb-07 7:50 
AnswerRe: How Create Load time DLLs on .net PinmemberPortatofe2-Oct-08 5:56 
AnswerRe: How Create Load time DLLs on .net PinmemberR.selvam8-Sep-09 0:29 
GeneralStatic .lib Help PinmemberArunAntony17-Mar-06 20:24 
Questionwrong run time dynamic linking example? PinmemberAlenkaZajka22-Jun-05 23:46 
GeneralCannot find the procedure in the DLL PinmemberNightfox4-Apr-05 18:17 
GeneralRe: Cannot find the procedure in the DLL PinmemberR.selvam4-Apr-05 19:09 
GeneralRe: Cannot find the procedure in the DLL PinmemberFrank K1-Nov-05 5:20 
GeneralDLL export for template base classes PinmemberJafar amiri3-Oct-04 0:55 
GeneralRe: DLL export for template base classes PinmemberR.selvam4-Apr-05 19:05 
QuestionHow to link implicitly a foreign DLL PinmemberCEERI1-Oct-04 0:10 
AnswerRe: How to link implicitly a foreign DLL PinsussAnonymous1-Oct-04 4:02 
QuestionHow to export functions PinmemberMichael Olsen17-Mar-04 23:40 
AnswerRe: How to export functions Pinmemberbdiamond23-Mar-04 3:18 
GeneralIn MFC Which DLL use PinmemberR.selvam15-Dec-03 18:32 
Questiondlls,lib,headers??? PinmemberNadia Tariq15-Dec-03 17:55 
AnswerRe: dlls,lib,headers??? PinmemberR.selvam16-Dec-03 5:46 
GeneralPros and Cons PinmemberMike Wild9-Dec-03 22:27 
GeneralRe: Pros and Cons PinmemberR.selvam30-Dec-03 11:34 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 8 Dec 2003
Article Copyright 2003 by R.selvam
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid