简体   繁体   中英

How to pass function pointer as lpParameter to CreateThread?

I have the following function which will be called by CreateThread:

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

    // call handleFunction()
    handleFunction(prio);

    return TRUE;
}

And I create the thread here:

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;
}

I get the following error when I am builind it:

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

What am I doing it wrong?

Passing &handleFunction to CreateThread() is wrong, because you are passing the local address of the handleFunction variable itself, not the address of the so_handler that it is pointing at.

Since handleFunction is already a pointer, try something more like this instead:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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