Assign C++ instance method to a global-function-pointer?

做~自己de王妃 提交于 2019-11-29 11:45:46
Matthew Flaschen

This is answered in the C++ FAQ, [1]. This doesn't work, because the pointer isn't associated with a particular object instance. The solution is given there too, create a global function that uses a particular object:

 Sacm* sacm_global;

 void sacm_global_paintPixel(int x,int y,int index)
 {
   sacm_global->paintPixel(x, y, index);
 }

void Sacm::doDetection()
{
  putPixelCallBack = &sacm_global_paintPixel;
  //call somefunctions in 'libBase' C library
}

You have to somehow setup the global variable properly.

You cannot convert an instance method pointer to a normal function pointer. A workaround is to use another global variable to hold the instance and a global wrapper function that is used as the callback and then in turn calls the instance method:

Sacm *callbackSacm;

extern "C"  // since it sounds like it's called from a C library
void call_paintPixel(int x, int y, int index) {
   callbackSacm->paintPixel(x, y, index);
}

void Sacm::doDetection() {
   callbackSacm = this;
   putPixelCallBack = call_paintPixel;
}

You can alternatively use a static member function. The address of a static member function can be taken and assigned to a regular function pointer, because no this pointer is implicitly passed to it -- under the hood, these functions operate just like regular non-member functions. But they have advantages over non-member functions:

  • A static method still has access to the private and protected members of any object of its class type.
  • A static method can be private or protected so access to it can be controlled.
  • Using a static method lets you and group functionality inside the class, where it belongs.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!