CreateThread 将 long 传递给 lpParameter
编译器在第 3 行说“非法间接”。IDE 说“表达式必须是指向完整对象类型的指针”
001 DWORD WINAPI MyCallbackFunction( LPVOID lpvParam )
002 {
003 long value = (long) *lpvParam;
004 ...
005 return 0;
006 }
007
008 BOOL StartMyThread( long value )
009 {
010 DWORD dwThreadId;
011 BOOL result = FALSE;
012 HANDLE hThread = NULL;
013 hThread = CreateThread(NULL, 0, MyCallbackFunction, &value, NULL, &dwThreadId );
014 result = (NULL == hThread);
015 CloseHandle( hThread );
016 return result;
017 }
如果我将第 3 行更改为此,它可以编译,但会崩溃...
long value = (long) lpvParam;
Compiler is saying "illegal indirection" on line 3. The IDE says "expression must be a pointer to a complete object type"
001 DWORD WINAPI MyCallbackFunction( LPVOID lpvParam )
002 {
003 long value = (long) *lpvParam;
004 ...
005 return 0;
006 }
007
008 BOOL StartMyThread( long value )
009 {
010 DWORD dwThreadId;
011 BOOL result = FALSE;
012 HANDLE hThread = NULL;
013 hThread = CreateThread(NULL, 0, MyCallbackFunction, &value, NULL, &dwThreadId );
014 result = (NULL == hThread);
015 CloseHandle( hThread );
016 return result;
017 }
If I change line 3 to this, it compiles, but crashes...
long value = (long) lpvParam;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您正在尝试引用
void*
指针,这是不允许的。您必须首先将其转换为另一种指针类型。由于您的参数是指向 long 的指针,因此您需要这样做:或者,如果线程不需要访问原始变量:
不过,Seth 是对的。当线程实际开始运行时,原始变量将消失。如果您尝试将其值传递给线程,请执行以下操作:
You are trying to deference a
void*
pointer, which is not allowed. You have to cast it to another pointer type first. Since your parameter is a pointer to along
, you need to do this instead:Or, if the thread does not need access to the original variable:
Seth is right, though. The original variable will be gone by the time the thread actually starts running. If you are trying to pass its value to the thread, do this instead: