首页 文章

如何将整数传递给CreateThread()?

提问于
浏览
7

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

2 回答

  • 5

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

    // 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
    }
    
  • 1

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

    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);
    

相关问题