Casting to a struct from LPVOID - C

Posted by Jamie Keeling on Stack Overflow See other posts from Stack Overflow or by Jamie Keeling
Published on 2010-03-11T18:30:20Z Indexed on 2010/03/11 18:34 UTC
Read the original article Hit count: 314

Filed under:
|

Hello,

I am writing a simple console application which will allow me to create a number of threads from a set of parameters passed through the arguments I provide.

DWORD WINAPI ThreadFunc(LPVOID threadData)
{
}

I am packing them into a struct and passing them as a parameter into the CreateThread method and trying to unpack them by casting them to the same type as my struct from the LPVOID.

I'm not sure how to cast it to the struct after getting it through so I can use it in the method itself, i've tried various combinations (Example attatched) but it won't compile.

Struct:

#define numThreads 1

struct Data
{
    int threads;
    int delay;
    int messages;
};

Call to method:

HANDLE hThread;
    DWORD threadId;
    struct Data *tData;

    tData->threads = numThreads;
    tData->messages = 3;
    tData->delay = 1000;


    // Create child thread
    hThread = CreateThread(
                            NULL,       // lpThreadAttributes (default)
                            0,          // dwStackSize (default)
                            ThreadFunc, // lpStartAddress
                            &tData,     // lpParameter
                            0,          // dwCreationFlags
                            &threadId   // lpThreadId (returned by function)
                           );

My attempt:

DWORD WINAPI ThreadFunc(LPVOID threadData)
    {
        struct Data tData = (struct Data)threadData;

        int msg;

        for(msg = 0; msg<5; msg++)
        {
            printf("Message %d from child\n", msg);
        }
        return 0;
}

Compiler error:

error C2440: 'type cast' : cannot convert from 'LPVOID' to 'Data'

As you can see I have implemented a way to loop through a number of messages already, I'm trying to make things slightly more advanced and add some further functionality.

© Stack Overflow or respective owner

Related posts about winapi

Related posts about c