Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将整数传递给CreateThread()?_C++_Int_Createthread - Fatal编程技术网

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

C++ 如何将整数传递给CreateThread()?,c++,int,createthread,C++,Int,Createthread,如何将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' warni

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

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

// 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
}
//堆上的参数,以避免可能的线程错误
int*id=新的int(1);
CreateThread(NULL,NULL,mHandler,id,NULL,NULL);
DWORD WINAPI mHandler(LPVOID sId){
//为方便起见,复制参数
int id=*静态_转换(sId);
删除sId;
//现在用id做点什么
}

您可以使用适当的类型消除此警告。在这种情况下,使用INT_PTR或DWORD_PTR(或任何其他_PTR类型)类型代替INT(请参见MSDN中的)

DWORD-WINAPI-mHandler(lpp)
{
INT_PTR id=重新解释铸件(p);
}
...
INT_PTR id=123;
CreateThread(NULL,NULL,mHandler,reinterpret_cast(id),NULL,NULL);
我会使用
CreateThread(…,reinterpret_cast(static_cast(id)),…)
在你的线程函数里面
int my_int=static_cast(重新解释强制转换(sId))

这也适用于枚举,而不是
int

它应该同时在32位和64位模式下工作。

如果线程超出
id
@ZdeslavVojkovic的范围,则会出现问题:不,没有。函数中的第一件事是通过值进行复制。它仍然不安全。如果新线程在ID超出作用域之前未计划,该怎么办(这可能是在
CreateThread
调用之后发生的?抱歉,但它不能正常工作。我在调试器中查看,看到:我进入CreateThread 0->并接收0,然后1->-858993460,程序崩溃…好的,使用
new
delete
是安全的,但现在它足以发送
id
,而不是
&id
-这应该在代码示例中修复,因为线程函数假定它接收到
int*
而不是
int**
。这也是BArtWell在调试程序中看到这些值/崩溃的原因。参数类型可能会使警告和错误静音,但不会修复代码。如果过程需要
DW的地址ORD
作为一个参数,那么你应该给它一个
DWORD
的地址,而不仅仅是将一个“任意”值转换成一个地址。官方文档声明,你可以传递一个标量值而不是指针。有些人使用一个老式的C转换,但我不喜欢。出于某种原因,你可以使用静态的将INT_PTR强制转换为INT,但不能将LPVOID静态转换为INT。因此,在第一步中,我将重新解释将LPVOID强制转换为INT_PTR。两者都是指针,因此大小相同(在x86模式下编译时为32位,在64位模式下编译时为64位)。此后,我将静态转换为INT(即32位)。这没有问题,除非有人传入的不是int,而是64位的值。
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);