如何将函数指针作为lpParameter传递给CreateThread?

时间:2017-03-14 18:01:57

标签: c++ windows winapi

我有以下函数,将由CreateThread调用:

DWORD WINAPI start_thread(LPVOID handleFunction)
{
    int prio = 4;

    // call handleFunction()
    handleFunction(prio);

    return TRUE;
}

我在这里创建了一个主题:

DECL_PREFIX tid_t so_fork(so_handler *handleFunction, unsigned priority) {

    DWORD dw;


    hThr[currentThread] = CreateThread(
        NULL,                                       // default security attributes
        0,                                          // use default stack size  
        (LPTHREAD_START_ROUTINE)start_thread,       // thread function name
        (LPVOID)&handleFunction,                        // argument to thread function 
        0,                                          // use default creation flags 
        &dw);           // returns the thread identifier 

    return 0;
}

我在构建它时遇到以下错误:

Error   C2064   term does not evaluate to a function taking 1 arguments libscheduler    

expression preceding parentheses of apparent call must have (pointer-to-) function type libscheduler

我做错了什么?

1 个答案:

答案 0 :(得分:1)

&handleFunction传递给CreateThread()是错误的,因为您传递的是handleFunction变量本身的本地地址,而不是它所指向的so_handler的地址

由于handleFunction已经是一个指针,请尝试更类似的东西:

DWORD WINAPI start_thread(LPVOID handleFunction)
{
    int prio = 4;

    // call handleFunction()
    so_handler *handler = (so_handler *) handleFunction;
    handler(prio); // or maybe (*handler)(prio), depending on how so_handler is actually defined...

    return TRUE;
}

DECL_PREFIX tid_t so_fork(so_handler *handleFunction, unsigned priority) {

    DWORD dw;

    hThr[currentThread] = CreateThread(
        NULL,                    // default security attributes
        0,                       // use default stack size  
        &start_thread,           // thread function name
        handleFunction,          // argument to thread function 
        0,                       // use default creation flags 
        &dw);                    // returns the thread identifier 

    return 0;
}