Using Dynamic-Link Libraries: Program Examples
The following examples demonstrate how to create and use a DLL.
Creating a Simple Dynamic-Link Library Example
The following example is the source code needed to create a simple DLL, Myputs.dll. It defines a simple string-printing function called myPuts(). The Myputs 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. To build the DLL, follow the directions in the documentation included with your development tools.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed. Click the OK button.
Click the Next button.
Select the DLL radio button for the Application type: and Empty project for the Additional options:. Click the Finish button.
Then, add the source file and give it a suitable name.
Next, add the following source code.
// The myPuts 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.
#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 myPuts(LPWSTR lpszMsg)
{
DWORD cchWritten;
HANDLE hConout;
BOOL fRet;
// Get a handle to the console output device.
hConout = CreateFileW(LCONOUT$,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (INVALID_HANDLE_VALUE == hConout)
return EOF;
wprintf(LI'm in DLL lor, with myPuts() that can be exported!\n);
wprintf(LI'm displaying a text sent to me by executable...\n);
wprintf(L\);
// Write a null-terminated string to the console output device
while (*lpszMsg != L'\0')
{
fRet = WriteConsole(hConout, lpszMsg, 1, &cchWritten, NULL);
if( (fRet == FALSE) || (cchWritten != 1) )
return EOF;
lpszMsg++;
}
wprintf(L\\n);
return 1;
}
#ifdef __cplusplus
}
#endif
Build and run the project. The following screenshot is a sample window, asking the executable (application) to be run (at this stage, we do not have the executable yet, that can import or use the function in the DLL). Just dismiss the window.
Under the project's Debug folder, the DLL and lib files should be generated and ready to be used.