Function pointers in C ++

I used the CreateThread function to write a class, for example C # BackgroundWorker in C ++. My code is:

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 derived from BackgroundWorker:

ListenThread.cpp:

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

But this line gives me the following error:

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

+5
source share
2 answers

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

Unfortunately this will not help. CreateThread does not work with (non-static) member functions. The solution is to create a static method to use as the actual function to start the stream.

Check out 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; } 
+1
source

The function pointer that CreateThread expects must have this signature:

 DWORD WINAPI ThreadProc(LPVOID lpParameter); 

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

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

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

+3
source

Source: https://habr.com/ru/post/1244723/


All Articles