Как передать целое число в CreateThread ()?

Как передать параметр int в функцию обратного вызова CreateThread? Я попробую:

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

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

Но я получаю предупреждения:

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

7

Решение

Передайте адрес целого числа вместо его значения:

// 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
}
5

Другие решения

Вы можете убрать это предупреждение, используя соответствующие типы. В этом случае используйте тип int_PTR или DWORD_PTR (или любой другой тип _PTR) вместо int (см. Типы данных Windows в 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);
1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector