Using the DLL
The following application code example demonstrates the use of the DLL functions defined in the previous example.
Create a new empty Win32 console application project. Give a suitable project name and change the project location if needed.
Then, add the source file and give it a suitable name.
Next, add the following source code.
#include <windows.h>
#include <stdio.h>
#define THREADCOUNT 4
#define DLL_NAME LTheTLSDLL
void ErrorExit(LPSTR);
extern C BOOL WINAPI StoreData(DWORD dw);
extern C BOOL WINAPI GetData(DWORD *pdw);
DWORD WINAPI ThreadFunc(void)
{
int i;
if(!StoreData(GetCurrentThreadId()))
ErrorExit(StoreData() error);
for(i=0; i<THREADCOUNT; i++)
{
DWORD dwOut;
if(!GetData(&dwOut))
ErrorExit(GetData() error);
if( dwOut != GetCurrentThreadId())
wprintf(Lthread %d: data is incorrect (%d)\n, GetCurrentThreadId(), dwOut);
else
wprintf(Lthread Id %d: data is correct\n, GetCurrentThreadId());
Sleep(0);
}
return 0;
}
int wmain(void)
{
DWORD IDThread;
HANDLE hThread[THREADCOUNT];
int i;
HMODULE hm;
// Load the DLL
hm = LoadLibrary(DLL_NAME);
if(!hm)
{
ErrorExit(DLL (LoadLibrary()) failed to load!\n);
}
wprintf(LLoadLibray() is fine, the %s DLL was loaded..\n, DLL_NAME);
// Create multiple threads
for (i = 0; i < THREADCOUNT; i++)
{
hThread[i] = CreateThread(NULL, // default security attributes
0, // use default stack size
(LPTHREAD_START_ROUTINE) ThreadFunc, // thread function
NULL, // no thread function argument
0, // use default creation flags
&IDThread); // returns thread identifier
// Check the return value for success.
if (hThread[i] == NULL)
ErrorExit(CreateThread() error!\n);
}
WaitForMultipleObjects(THREADCOUNT, hThread, TRUE, INFINITE);
FreeLibrary(hm);
return 0;
}
void ErrorExit (LPSTR lpszMessage)
{
fwprintf_s(stderr, L%s\n, lpszMessage);
ExitProcess(0);
}
When you build, the following error should be expected.
1>------ Build started: Project: UseTheTLSDLL, Configuration: Debug Win32 ------
1>Compiling...
1>UseTheTLSDLLSrc.cpp
1>Compiling manifest to resources...
1>Microsoft (R) Windows (R) Resource Compiler Version 6.0.5724.0
1>Copyright (C) Microsoft Corporation. All rights reserved.
1>Linking...
1>UseTheTLSDLLSrc.obj : error LNK2019: unresolved external symbol _GetData@4 referenced in function unsigned long __stdcall ThreadFunc(void) (?ThreadFunc@@YGKXZ)
1>UseTheTLSDLLSrc.obj : error LNK2019: unresolved external symbol _StoreData@4 referenced in function unsigned long __stdcall ThreadFunc(void) (?ThreadFunc@@YGKXZ)
1>C:\amad\UseTheTLSDLL\Debug\UseTheTLSDLL.exe : fatal error LNK1120: 2 unresolved externals
1>Build log was saved at file://c:\amad\UseTheTLSDLL\UseTheTLSDLL\Debug\BuildLog.htm
1>UseTheTLSDLL - 3 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Add the path to the DLL/lib and the library file name.
Build and run the application project. The following is a sample output.