简体   繁体   English

C ++ - 通过ref将对象传递给CreateThread()

[英]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. 我不确定这是什么正确的语法,因为它涉及我不熟悉的winapi。 For example, i didnt know it won't let me xhangethe predefined thread function parameters from processClient(LPVOID) to processClient(LPVOID&). 例如,我不知道它不会让我将预定义的线程函数参数从processClient(LPVOID)更改为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()". 我需要通过引用传递“params”对象(就像现在没有问题,即使我不会改变其中的值)到线程函数“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 );
}

SOCKET ClientSocket=(SOCKET)*lpParam->sock; 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 '*'. lpParam具有与传递它时相同的值,在main中,它是'params',类型为'ClientParams *',因此您没有任何业务使用'*'取消引用它。 The rest of it is just a precedence problem. 其余部分只是一个优先问题。 It should be 它应该是

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

访问结构成员必须通过该结构。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM