gpt4 book ai didi

CreateThread 中的转换错误

转载 作者:行者123 更新时间:2023-11-30 14:54:49 26 4
gpt4 key购买 nike

当我尝试使用CreateThread函数时,我遇到了一个奇怪的错误。这是我的代码:

HANDLE threads[3];  //threads[0] is printer, threads[1] is receiver, [2] is serverconn
DWORD printer_id, receiver_id, serverconn_id;
if(
((threads [0] = CreateThread(NULL, 0, printer_thread, (LPVOID) thread_args, 0, &printer_id)) == NULL) ||
((recv_thread = threads [1] = CreateThread(NULL, 0, receiver_thread, (LPVOID) thread_args, 0, &receiver_id)) == NULL) ||
((threads [2] = CreateThread(NULL, 0, serverconn_thread, (LPVOID) thread_args, 0, &serverconn_id)) == NULL)
)
{
IO_print_line("Initialization error");
return FALSE;
}

printer_threadreceiver_threadserverconn_thread 的函数定义如下:

int serverconn_thread(LPVOID args);

Visual Studio 编译器给我这个错误:

Error   C2440   'function': cannot convert from 'int (__cdecl *)(LPVOID)' to 'LPTHREAD_START_ROUTINE'

我真的不明白,因为我认为我已经完全做到了 what the official documentation suggests

不,将线程函数的返回类型更改为 DWORD 并不能解决任何问题,错误只会更改为:

Error   C2440   'function': cannot convert from 'DWORD (__cdecl *)(LPVOID)' to 'LPTHREAD_START_ROUTINE'

奇怪的是,如果我像这样改变它:

if(
((threads [0] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) &printer_thread, (LPVOID) thread_args, 0, &printer_id)) == NULL) ||
((recv_thread = threads [1] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) &receiver_thread, (LPVOID) thread_args, 0, &receiver_id)) == NULL) ||
((threads [2] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) &serverconn_thread, (LPVOID) thread_args, 0, &serverconn_id)) == NULL)
)

通过强制转换,编译器没问题,但我认为以这种方式强制转换不是一个好主意。我该如何解决这个问题?

最佳答案

您没有关注official documentation当声明你的线程函数时。

您的原始声明使用 int 作为返回值,并使用 __cdecl (隐式)作为调用约定。当您将返回值更改为DWORD时,您没有更改调用约定。

但是,documentation清楚地显示了正确的声明:

DWORD WINAPI ThreadProc(  _In_ LPVOID lpParameter);

DWORD is an unsigned long, and WINAPI is a macro that maps to the __stdcall calling convention (see Windows Data Types).

So, the correct declaration of your functions would be:

unsigned long __stdcall printer_thread(void *args);
unsigned long __stdcall receiver_thread(void *args);
unsigned long __stdcall serverconn_thread(void *args);

但是,由于 CreateThread() 采用 LPTHREAD_START_ROUTINE 作为输入,该输入被声明为 DWORD (WINAPI*)(LPVOID)(请参阅winbase.h 中的实际声明),您应该声明您的函数以匹配:

DWORD WINAPI printer_thread(LPVOID args);
DWORD WINAPI receiver_thread(LPVOID args);
DWORD WINAPI serverconn_thread(LPVOID args);

关于CreateThread 中的转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46458849/

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