shawn a
shawn a

Reputation: 809

C++ - Passing an object to CreateThread() by ref

I'm not sure what the correct syntax is for this because it involves the winapi which i'm not familiar with. For example, i didnt know it won't let me xhangethe predefined thread function parameters from processClient(LPVOID) to processClient(LPVOID&).

I need to pass the "params" object by reference(just so theres no problems for now, even though im not going to change values in it) to the thread function "processClient()".

... struct(the object) declaration
struct ClientParams{

    ClientParams::ClientParams():sock(INVALID_SOCKET), i(NULL){};

public:
    SOCKET sock;
    int i;
};

... in processClient(LPVOID lpParam){
    SOCKET ClientSocket=(SOCKET)*lpParam->sock; ?? doesnt work
    int i=*lpParam->i; ?? doesn't work
}
... in main{
ClientParams *params = new ClientParams();
params->i=some_value;
params->sock=ClientSocket;
CreateThread(
            NULL,                       // don't inherit handle
            0,                          // use default size for the executable
            processClient,
            (LPVOID)params,             // thread data
            0,                          // run right away
            &i );
}

Upvotes: 0

Views: 1070

Answers (2)

Lange
Lange

Reputation: 1

Access structure members must through the structure.

SOCKET ClientSocket=((ClientParams*)lpParam)->sock;

Upvotes: 0

user207421
user207421

Reputation: 310957

SOCKET ClientSocket=(SOCKET)*lpParam->sock; ?? doesnt work

lpParam has the same value it did when you passed it, in main, where it was 'params', of type 'ClientParams*', so you don't have any business dereferencing it with '*'. The rest of it is just a precedence problem. It should be

SOCKET ClientSocket=((ClientParams*)lpParam)->sock;

Upvotes: 2

Related Questions