Koustav Ghosal Koustav Ghosal - 26 days ago 10
C++ Question

Using DLL's in CPP

I am a newbie to CPP. I have a Visual studio project which creates a dll. I need to write a simple code which calls the functions in this dll.

Till now most of the questions I browsed dealt with problems where the dll was called from an external app.

I want a very simple tutorial that introduces this concept. It loads a dll once and then calls its functions repeatedly from a simple code and NOT an app.

A simple example or a link to it will be very helpful.

Thanks in advance

Answer Source

The basic concept is::

  1. LoadLibrary: To load the dll.
  2. GetProcAddress: To get the address of exported function of the dll.

MSDN Sample Code // Assuming you have correctly built DLL with exported functions. // A simple program that uses LoadLibrary and // GetProcAddress to access myPuts from Myputs.dll.

#include <windows.h> 
#include <stdio.h> 

typedef int (__cdecl *MYPROC)(LPWSTR); 

int main( void ) 
    HINSTANCE hinstLib; 
    MYPROC ProcAdd; 
    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE; 

    // Get a handle to the DLL module.

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

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

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

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

        if (NULL != ProcAdd) 
            fRunTimeLinkSuccess = TRUE;
            (ProcAdd) (L"Message sent to the DLL function\n"); 
        // Free the DLL module.

        fFreeResult = FreeLibrary(hinstLib); 

    // If unable to call the DLL function, use an alternative.
    if (! fRunTimeLinkSuccess) 
        printf("Message printed from executable\n"); 

    return 0;