Jump to content
Tuts 4 You

TLS callback example in C++


Aldhard Oswine

Recommended Posts

Aldhard Oswine
Posted (edited)

I have following code:

#include <Windows.h>
#include <cstdio>


__declspec(thread) int a;
void NTAPI on_tls_callback(PVOID h, DWORD dwReason, PVOID pv)
{
    a = 43;
    MessageBox(nullptr, L"aaaa", L"bbb", MB_OK);
}

#pragma data_seg(".CRT$XLB")
PIMAGE_TLS_CALLBACK p_thread_callback = on_tls_callback;
#pragma data_seg()

int main()
{
    printf("%d\n", a);

    getchar();
}

I want to execute on_tls_callback() before main, but it does not work on MSVC 2015.

Can you explain how can I use TLS callback?

Edited by Aldhard Oswine
Aldhard Oswine
Posted

This works:
 

#include <Windows.h>
#include <cstdio>
__declspec(thread) int a;
void NTAPI on_tls_callback(void* dll, DWORD reason, void* reserved)
{
	a = 543;
	MessageBox(nullptr, L"aaaa", L"bbb", MB_OK);
}

#pragma comment (linker, "/INCLUDE:__tls_used")
#pragma comment (linker, "/INCLUDE:__xl_b")
#pragma data_seg(".CRT$XLB")
EXTERN_C

PIMAGE_TLS_CALLBACK _xl_b = on_tls_callback;
#pragma data_seg()

int main()
{
	printf("%d\n", a);

	getchar();
}

 

  • Thanks 1

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...