gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 18:33:24 24 4
gpt4 key购买 nike

如何给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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com