c++ - 如何将 "this"指针传递给全局函数

标签 c++ constructor this visual-c++-2008

//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;

}

此处 pContext 接收“this”指针。我的尝试是访问 param1 和 param2
从这里开始工作 我该怎么做?

最佳答案

或者你可以让 functionExecuter 成为 AsynchronousFunction 的友元 或者 在 AsynchronousFunction 中添加一个公共(public)函数,它执行所需的操作并从 functionExecuter 中调用它,如下所示。

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

关于c++ - 如何将 "this"指针传递给全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21844440/

相关文章:

javascript - jQuery $(this) 引用未定义

javascript - “this”关键字如何工作?

java - 使用 lombok 注释的继承会出错

c++ - 在C++代码的编译器中出现错误,详细内容在

c++ - 给定一个 dll/exe(带或不带 .pdb),我可以看到哪些 .obj 文件对其大小有影响吗?

c++ - << 运算符抛出编译错误

c++ - 与 get_instance() 分离的单例构造函数

c# - C#中构造函数的返回类型是什么?

javascript - "this"在 ES6 的箭头函数中指的是什么?

c++ - fortran代码调用c代码时出错