Search code examples
c++visual-c++-2010

CreateThread passing long to lpParameter


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;

Solution

  • 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 a long, you need to do this instead:

    long *value = (long*) lpvParam;
    

    Or, if the thread does not need access to the original variable:

    long value = * (long*) lpvParam;
    

    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:

    // notice the '&' operator is gone now...
    hThread = CreateThread(NULL, 0, MyCallbackFunction, (LPVOID)value, NULL, &dwThreadId );
    ...    
    long value = (long) lpvParam;