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
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
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With