Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass integer to CreateThread()?

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
like image 463
BArtWell Avatar asked Sep 26 '12 08:09

BArtWell


2 Answers

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
}
like image 135
Jon Avatar answered Oct 04 '22 18:10

Jon


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);
like image 34
sdkljhdf hda Avatar answered Oct 04 '22 17:10

sdkljhdf hda