8

如何将 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
4

3 回答 3

6

传递整数的地址而不是其值:

// 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
}
于 2012-09-26T08:06:37.287 回答
2

您可以通过使用适当的类型来消除此警告。在这种情况下,使用 INT_PTR 或 DWORD_PTR(或任何其他 _PTR 类型)类型而不是 int(请参阅MSDN 中的Windows 数据类型)。

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);
于 2012-09-26T09:38:57.050 回答
0

我会 CreateThread(..., reinterpret_cast<LPVOID>(static_cast<INT_PTR>(id)), ...); 在你的线程函数中使用 and int my_int = static_cast<int>(reinterpret_cast<INT_PTR>(sId));

这也适用于枚举而不是int. 它应该可以在 32 位和 64 位模式下工作。

于 2021-05-05T12:20:56.623 回答