Note that there are some explanatory texts on larger screens.

plurals
  1. POC++ class: pointer to a non-static func
    primarykey
    data
    text
    <p>This is my <a href="https://stackoverflow.com/questions/7490219/c-class-object-that-creates-thread-pointer-to-the-function-access-violatio">last question</a>. I try to improve my class Thread. Constructor receives pointer to the function, that must run in a new thread. </p> <pre><code>class Thread { public: Thread(void (*p)()) { pf=p; } ~Thread () {} void StartThread() { hThread = (HANDLE)_beginthreadex( NULL, 0, ThreadProc, NULL, 0, &amp;threadID); } private: void (*pf)(); HANDLE hThread; unsigned threadID; static unsigned WINAPI ThreadProc(LPVOID lpParam) { (*pf)(); //error C2597 illegal reference to non-static member return 0; } }; </code></pre> <p>In ThreadProc I need to call TimerFunc. </p> <pre><code>void TimerFunc () { i++; } </code></pre> <p>Example of usage this class:</p> <pre><code>Thread *timer; timer = new Thread(TimerFunc); timer-&gt;StartThread(); </code></pre> <p>So it doesn't work. Please somebody tell me, if this class is foolish. May be it is a bad idea to send pointer to func which is situated outside class?? Thank you. </p> <p>Thanks very much for your advices! Now it works! </p> <pre><code>class Thread { public: Thread(void (*p)()) { gg.pf=p; } ~Thread (); void StartThread() { hThread = (HANDLE)_beginthreadex( NULL, 0, ThreadProc, this, 0, &amp;threadID); } private: struct mm { Thread *pThread; void (*pf)(); } gg; HANDLE hThread; unsigned threadID; static unsigned WINAPI ThreadProc(LPVOID lpParam) { mm hh; hh.pThread=static_cast&lt;Thread*&gt; (lpParam); hh.pf=hh.pThread-&gt;gg.pf; hh.pf(); return 0; } }; </code></pre> <p>What do you think? Is it correct choice?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload