简体   繁体   English

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

[英]How to pass integer to CreateThread()?

How to pass int parameter to CreateThread callback function? 如何将int参数传递给CreateThread回调函数? I try it: 我试试看:

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

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

But I get warnings: 但我收到警告:

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

Pass the address of the integer instead of its value: 传递整数的地址而不是其值:

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

You can make this warning go away by using appropriate types. 您可以使用适当的类型使此警告消失。 In this case use INT_PTR or DWORD_PTR (or any other _PTR type) type instead of int (see Windows Data Types in MSDN). 在这种情况下,使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM