Question

How to pass int parameter to CreateThread callback function? I try it:

DWORD WINAPI mHandler(LPVOID sId) {
...
arr[(int)sId]
...
}

int id=1;
CreateThread(NULL, NULL, mHandler, (LPVOID)id, NULL, NULL);

But I get warnings:

warning C4311: 'type cast' : pointer truncation from 'LPVOID' to 'int'
warning C4312: 'type cast' : conversion from 'int' to 'LPVOID' of greater size
Was it helpful?

Solution

Pass the address of the integer instead of its value:

// parameter on the heap to avoid possible threading bugs
int* id = new int(1);
CreateThread(NULL, NULL, mHandler, id, NULL, NULL);


DWORD WINAPI mHandler(LPVOID sId) {
    // make a copy of the parameter for convenience
    int id = *static_cast<int*>(sId);
    delete sId;

    // now do something with id
}

OTHER TIPS

You can make this warning go away by using appropriate types. In this case use INT_PTR or DWORD_PTR (or any other _PTR type) type instead of int (see Windows Data Types in MSDN).

DWORD WINAPI mHandler(LPVOID p)
{
    INT_PTR id=reinterpret_cast<INT_PTR>(p);
}
...

INT_PTR id = 123;
CreateThread(NULL, NULL, mHandler, reinterpret_cast<LPVOID>(id), NULL, NULL);

I would use CreateThread(..., reinterpret_cast<LPVOID>(static_cast<INT_PTR>(id)), ...); and inside your thread function int my_int = static_cast<int>(reinterpret_cast<INT_PTR>(sId));

This also works with enums instead of int. It should work in both 32- and 64-bit mode.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top