How to create a stream using the non-stationary method in vC ++ mfc

I create a stream using this call:

m_pThread=AfxBeginThread(read_data,(LPVOID)hSerial); 

read_data is a static method in my class.

But I want to call a non-stationary method and create a thread.

How I want to share a variable between this thread and one of my class methods.

I tried to take a static variable, but it gave some errors.

+4
source share
2 answers

You cannot create a stream using a non-static member of a function as a stream procedure: the reason is that all non-static methods of the class have an implicit first argument, this is a pointer to this.

it

 class foo { void dosomething(); }; 

actually

 class foo { void dosomething(foo* this); }; 

Because of this, the function signature does not match the one you need for the stream procedure. You can use the static method as a stream procedure and pass it to this pointer. Here is an example:

 class foo { CWindThread* m_pThread; HANDLE hSerial; static UINT MyThreadProc(LPVOID pData); void Start(); }; void foo::Start() { m_pThread=AfxBeginThread(MyThreadProc,(LPVOID)this); } UINT foo::MyThreadProc(LPVOID pData) { foo* self = (foo*)pData; // now you can use self as it was this ReadFile(self->hSerial, ...); return 0; } 
+4
source

I will not repeat what Marius said, but add that I am using the following:

 class foo { CWindThread* m_pThread; HANDLE hSerial; static UINT _threadProc(LPVOID pData); UINT MemberThreadProc(); void Start(); }; void foo::Start() { m_pThread=AfxBeginThread(_threadProc,(LPVOID)this); } UINT foo::MyThreadProc(LPVOID pData) { foo* self = (foo*)pData; // call class instance member return self->MemberThreadProc(); } UINT foo::MemberThreadProc() { // do work ReadFile(hSerial, ...); return 0; } 

I follow this pattern every time I use streams in classes in MFC applications. Thus, I have the convenience of having all members similar to me in the class itself.

+4
source

All Articles