Reputation: 63250
I'm learning about Thread Local Storage... (TLS) Here is my TLS Alloc code:
//global variable
DWORD g_dwTlsIndex;
//inside DLLMain:
int val= 5;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
g_dwTlsIndex = TlsAlloc();
if ((g_dwTlsIndex = TlsAlloc()) == TLS_OUT_OF_INDEXES)
{
printf("No more indexes available");
}
void *pint;
memcpy(&pint, &val, sizeof val);
TlsSetValue(g_dwTlsIndex, pint);
break;
Now I try to get the value from the TLS: (in another CPP file)
// declare index value...
extern DWORD g_dwTlsIndex;
int data;
LPVOID d;
d = TlsGetValue(g_dwTlsIndex);
memcpy(&data, &d, sizeof d);
printf("Data: %d", data);
But data contains 0, where I put 5 in it.... What have I done wrong?
Upvotes: 0
Views: 1382
Reputation: 68681
I assume that val
is local to DllMain
?
What version of Windows are you running? 64-bit Windows has 64-bit pointers and 32-bit int
, so all the memcpy
calls will be incorrect. Rather than using memcpy
, just cast the values directly:
TlsSetValue(g_dwTLSIndex,(LPVOID)5);
int data=(int)TlsGetValue(g_dwTLSIndex);
Upvotes: 0
Reputation: 639
A few notes:
Your error checking statement should read:
if (g_dwTLSIndex == TLS_OUT_OF_INDEXES).
As it stands, you're assigning g_dwTlsIndex twice (and thus losing the reference with the first assignment.)
Do some basic debugging:
These steps should help you find the problem.
Upvotes: 1