|< Dynamic Link Library, DLL 2 | Main | Dynamic Link Library, DLL 4 >| Site Index | Download |


 

 

 

 

MODULE CC1

DYNAMIC LINK LIBRARY - DLL

Part 3: PROGRAM EXAMPLES

 

 

 

What do we have in this Module?

  1. Creating a Simple Dynamic-Link Library Program

  2. Using Load-Time Dynamic Linking

  3. Using Run-Time Dynamic Linking

 

 

My Training Period: aa  hours. Before you begin, read some instruction here. The Windows MFC programming (GUI programming) for DLL can be found at MFC GUI Programming Step-by-step Tutorial.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

The Win32 programming skills:

  • Able to understand, build and run the dynamic-link library programs.

  • Able to differentiate between the static and dynamic linking.

  • Able to recognize different types of the DLL.

  • Able to create exported and imported functions of DLL.

Creating a Simple Dynamic-Link Library Program

 

The following snapshots demonstrate how to create and use a DLL. Firstly let go through the steps how to create DLL project.

 

Select the Win32 console Project and put the project name.

 

How-to, step-by-step createtng dynamic link library project, program examples

 

Select the DLL radio button and tick the Empty project.

 

How-to, step-by-step createtng dynamic link library - selecting empty DLL project

 

Then add the C++ source file as usual.

 

How-to, step-by-step createtng dynamic link library project: Adding source file

 

 

How-to, step-by-step createtng dynamic link library project: Typing the source file name

 

Copy and paste the following source code. Just build, do not run. Later on, we are going to create an application that will use mydll() function in our DLL program. Next we are ready to build our DLL program. In this example we build the Release version.

The following example, mysrcdll.cpp, is the source code needed to create a simple DLL, mydllpro.dll. The file mysrcdll.cpp contains a simple string-printing function called mydll(). The mydllpro.dll does not define an entry-point function, because it is linked with the C run-time library and has no initialization or cleanup functions of its own to perform.

// Project name: mydllpro, File name: mysrcdll.cpp, generating mydllpro.dll, mydllpro.lib...

// The mydll function writes a null-terminated string to

// the standard output device...

// The export mechanism used here is the __declspec(export)

// method supported by Microsoft Visual Studio, but any

// other export method supported by your development

// environment may be substituted.

// For WinXp, don't forget to add

// Advapi32.lib library if needed...

#define _WIN32_WINNT 0x0501

#include <windows.h>

#include <stdio.h>

#define EOF (-1)

#ifdef __cplusplus    // If used by C++ code,

extern "C" {          // we need to export the C interface

#endif

 

__declspec(dllexport) int mydll(LPTSTR lpszMsg)

{

    DWORD cchWritten;

    HANDLE hStdout;

    BOOL fRet;

 

       printf("-This is mydll.dll file lol!-\n");

       // Get a handle to the standard output device.

       hStdout = GetStdHandle(STD_OUTPUT_HANDLE);

       if (INVALID_HANDLE_VALUE == hStdout)

       {

              // failed to get the handle, give some message, get error code, just exit...

              printf("GetStdHandle(), invalid handle, error: GetLastError().\n");

              return EOF;

       }

       else

              printf("GetStdHandle(), standard handle is OK.\n");

    // Write a null-terminated string to the standard output device.

    while (*lpszMsg != '\0')

    {

        fRet = WriteFile(hStdout, lpszMsg, 1, &cchWritten, NULL);

        if ((fRet == FALSE) || (cchWritten != 1))

            // If something wrong just exit or provide meaningful message/error code...

            return EOF;

            // else, write more...

           lpszMsg++;

    }

       printf("\n");

    return 1;

}

#ifdef __cplusplus

}

#endif

Setting the Release version.

 

How-to, step-by-step createtng dynamic link library project: Changing the project to release version

 

Or use Configuration Manager…

 

How-to, step-by-step createtng dynamic link library project: Changing the project to release version

 

How-to, step-by-step createtng dynamic link library project: Changing the project to release version

 

Well, finally let build the program. Then, verify the DLL file (mydllpro.dll) creation that is ready to be used. Notice the mydllpro.lib file that will be used in implicit linking (loading).

 

How-to, step-by-step createtng dynamic link library project: The generated DLL and LIB file

 

Using Load-Time Dynamic Linking

 

After you have created a DLL, you can use it in an application. The following file, mydllloadtime.cpp, is the source code for an empty Win32 console application that uses the mydll() function exported from mydll.dll. Take note that we don’t have any user defined header file in our previously created DLL program.

// File: mydllloadtime.cpp

// A simple program that uses mydll() from mydllpro.dll.

// For WinXp, don't forget to add

#define _WIN32_WINNT 0x0501

#include <windows.h>

 

// call to a function in the mydllpro.dll

__declspec(dllimport) int mydll(LPTSTR);

// Another form: int mydll(LPTSTR);

 

int main()

{

    int Ret = 1;

    Ret = mydll("This message was printed using the DLL function");

    return Ret;

}

Because mydllloadtime.cpp calls the DLL function implicitly, the module for the application must be linked with the import library mydllpro.lib. In this example the mydllpro.lib and mydllpro.dll were copied to the project directory.

 

How-to, step-by-step createtng dynamic link library project: Adding dependencies (library) to Visual C++ project

 

Unfortunately, this program failed when mydll() call is made although all the required steps have been followed. The error is shown below:

        ...

        ...

        Loaded kernel32.lib(KERNEL32.dll)

      Found __NULL_IMPORT_DESCRIPTOR

        Referenced in kernel32.lib(KERNEL32.dll)

        Loaded kernel32.lib(KERNEL32.dll)

      Found KERNEL32_NULL_THUNK_DATA

        Referenced in kernel32.lib(KERNEL32.dll)

...

...

testdll.obj : error LNK2019: unresolved external symbol "int __cdecl mydll(char *)" (?mydll@@YAHPAD@Z) referenced in function _main

Release/mydlltest.exe : fatal error LNK1120: 1 unresolved externals

From the build output, the library file has been searched but not loaded/processed. Tenouk did not try this example on Visual C++ compiler. Let try using the same code for Run-Time Dynamic Linking.

 

Using Run-Time Dynamic Linking

 

You can use the same DLL in both load-time and run-time dynamic linking. The following source code produces the same output as the load-time example in the previous section. The program uses the LoadLibrary() function to get a handle to mydll.dll. If LoadLibrary() succeeds, the program uses the returned handle in the GetProcAddress() function to get the address of the DLL's mydll() function.

 

After calling the DLL function, the program calls the FreeLibrary() function to unload the DLL. The following example illustrates an important difference between run-time and load-time dynamic linking. If the mydll.dll file is not available, the application that using load-time dynamic linking simply terminates. The run-time dynamic linking example, however, can respond to the error.

 

This project is an empty console mode application. Copy the mydllpro.dll to the project directory or system directory or any other directory sequence as mentioned before. In this example the mydllpro.dll has been copied to the project directory.

 

// File:  testmydllruntime.cpp

// Using Run-Time Dynamic Linking

// A simple program that uses LoadLibrary() and

// GetProcAddress() to access mydll() in mydllpro.dll.

// For WinXp, don't forget to add

#define _WIN32_WINNT 0x0501

#include <stdio.h>

#include <windows.h>

 

typedef void (*MYPROC)(LPTSTR);

 

int main()

{

    HINSTANCE hinstLib;

    MYPROC ProcAdd;

    BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;

    // Get a handle to our DLL module created in the previous example.

    hinstLib = LoadLibrary("mydllpro");

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

    if (hinstLib != NULL)

    {

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

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

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

        if (ProcAdd != NULL)

        {

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

fRunTimeLinkSuccess = TRUE;

// Pass some text, mydll() will display it on the standard output...

(ProcAdd) ("\nThis message is via DLL function...\n");

        }

       else

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

// Free the DLL module.

fFreeResult = FreeLibrary(hinstLib);

        if (fFreeResult != 0)

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

        else

               printf("FreeLibrary() is not OK, error: %d.\n", GetLastError());

    }

    else

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

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

    if (!fRunTimeLinkSuccess)

        printf("This message via alternative method...\n");

    return 0;

}

 

A sample output:

Run-time dynamic linking program example output

 

 

Well it works! The program uses run-time dynamic linking; you should not link with the import library when creating this program as in our Load-Time Dynamic Linking example. Let proceed to more story.

 

 

 

 

 

 

 

 

 

 

 

 

 

Further reading and digging:

 

  1. Structure, enum, union and typedef story can be found C/C++ struct, enum, union & typedef.

  2. For Multibytes, Unicode characters and Localization please refer to Locale, wide characters & Unicode (Story) and Windows users & groups programming tutorials (Implementation).

  3. Windows data types are Windows data types.

  4. Microsoft Visual C++, online MSDN.

  5. Check the best selling C / C++ and Windows books at Amazon.com.

 

 

 

 

 

 

 

|< Dynamic Link Library, DLL 2 | Main | Dynamic Link Library, DLL 4 >| Site Index | Download |