Zarco
Zarco

Reputation: 175

How to pass "this" pointer to a global function

//This is AsynchronousFunction class header file

typedef int (*functionCall)(int, int);

DWORD __stdcall functionExecuter(LPVOID pContext); // global function

class  AsynchronousFunction
{   

  int param1, param2;
  functionCall fCall;
  HANDLE m_handle;

public:
  AsynchronousFunction(functionCall, int, int);
  ~AsynchronousFunction();
  int result();

protected:
private:
  int returnVal; 

};


It's implementation as follows

AsynchronousFunction::AsynchronousFunction(functionCall fCall, int param1, int       param2):m_handle(CreateEvent( NULL , false , false , NULL))
{
  bool b = QueueUserWorkItem(functionExecuter, this, WT_EXECUTEDEFAULT);

  WaitForSingleObject(m_handle, INFINITE);
  SetEvent(m_handle);
}

AsynchronousFunction::~AsynchronousFunction()
{
  CloseHandle(m_handle);
}

int AsynchronousFunction::result()
{

  return 0;// not implemented yet

}

DWORD __stdcall functionExecuter(LPVOID pContext)
{

  return 0;

}

here pContext receives "this" pointer. my attempt is access the param1 and param2
from here and do the work how can I do this ?

Upvotes: 0

Views: 253

Answers (2)

jia103
jia103

Reputation: 1134

@sajas Sorry, I don't have an explicit reference other than to refer to Scott Meyers' books or Herb Sutter books; it's just one of those things I picked up along the way. In general, you don't want to break encapsulation by exposing private data if it's not needed, which is exactly what friends do. In this case, if you decide to change the implementation of AsynchronousFunction tomorrow and functionExecuter was its friend, then it's more likely that you could break functionExecuter because it might have relied on the private members; on the other hand, if it was never a friend to begin with, you'd be forced to code functionExecuter using AsynchronousFunction's public interface only.

Upvotes: 0

Karthik Kalyanasundaram
Karthik Kalyanasundaram

Reputation: 1525

Either you can make the functionExecuter a friend of AsynchronousFunction OR Add a public function in AsynchronousFunction which does the required things and call it from functionExecuter, something like shown below.

DWORD __stdcall functionExecuter(LPVOID pContext)
{
  return (reinterpret_cast<AsyncrhonousFunction*>(pContext))->realFunctionExecuter();
}

Upvotes: 1

Related Questions