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

标签 c++ int createthread

如何给CreateThread回调函数传递int参数?我试了一下:

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

最佳答案

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

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

关于c++ - 如何将整数传递给 CreateThread()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12597205/

相关文章:

java - 将 C++ 构造函数翻译成 Java

c++ - 如何确保只输入 int 而不是 char?

C++ CreateThread 不显示结果

C++ CreateThread() LPSTR 参数错误 Windows 7 (64)

正确终止正在运行的线程 "works"

c++ - 为什么C++中同时存在struct和class?

c# - 将现有的 QWidget 停靠在 QWindow 中

c++ - 在cpp中的结构内部重载()运算符

c++ - 在 C++ 中声明 int 对象

java |将 2D int 数组转换为 2D char 数组以用于 println