Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers in C++

I used CreateThread function to write a class like C# BackgroundWorker in C++.My code:

BackgroundWorker.h:

class BackgroundWorker
{
    private :
        HANDLE _threadHandle;
        unsigned int _threadCallcounter;
        DWORD _threadID;
    public:
        BackgroundWorker();
        ~BackgroundWorker();
        virtual DWORD WINAPI Function(LPVOID vpPram);
}

BackgroundWorker.cpp:

#include "BackgroundWorker.h"
void BackgroundWorker::DoWork()
{
    this->_threadHandle = CreateThread(NULL,
        0,this->Function,&this->_threadCallcounter,
        0, &this->_threadID); // !!!***This part throws an error***!!!
}

Then I created another class that derived from BackgroundWorker:

ListenThread.cpp:

class ListenThread :public BackgroundWorker
{
    DWORD WINAPI Function(LPVOID vpPram)
    {
        //DO somthing...
        return 0;
    }
};

But that line gives me the following error:

non - standard syntax; use '&' to create a pointer to member

like image 205
Masoumi.Saeed Avatar asked Sep 25 '22 03:09

Masoumi.Saeed


2 Answers

The function pointer that CreateThread expects must have this signature:

DWORD WINAPI ThreadProc(LPVOID lpParameter);

When you create a member function it gets an invisible "this" parameter as first argument, so you declare something like this implicitly:

DWORD WINAPI ThreadProc(BackgroundWorker *this, LPVOID lpParameter);

Create a static member function to omit the this pointer and if you need that pointer inside the thread routine pass it as the void * parameter

like image 144
Serve Laurijssen Avatar answered Sep 28 '22 05:09

Serve Laurijssen


Your error message means you need to pass pointer to function as &Function, not Function in DoWork.

Unfortunately fixing this won't help. CreateThread doesn't work with (non-static) member functions. A solution is to create a static method to use as the actual thread start function.

Check this example:

#include <Windows.h>
#include <iostream>

class BackgroundWorker
{
private :
    HANDLE _threadHandle;
    DWORD _threadID;

public:
    static DWORD WINAPI StaticThreadStart(void * Param) {
        BackgroundWorker * This = static_cast<BackgroundWorker *>(Param);
        return This->Function();
    }

    virtual DWORD Function() {
        return 0;
    }

    void DoWork() {
        _threadHandle = CreateThread(NULL, 0, StaticThreadStart, this, 0, &_threadID);
    }
};

class ListenThread : public BackgroundWorker {
    DWORD Function() override {
        std::cout << "Working...\n";
        return 0;
    }
};

int main()
{
    ListenThread cl;
    cl.DoWork();

    // Call pause to wait for new thread in this example
    system("pause");
    return 0;
}
like image 40
Lukáš Bednařík Avatar answered Sep 28 '22 04:09

Lukáš Bednařík