且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 C++ 抽象类中将回调(用于 C 库)实现为纯虚拟

更新时间:2022-04-03 21:42:59

您的代码过于简单.在现实世界中,库函数"和回调都有一个 void* 用户数据"参数.您可以将指向您的类实例的指针传递到库函数"的用户数据"中,它将被转发到回调中,您可以在其中使用该指针访问对象.

Your code is oversimplified. In real world both the "library function" and the callback will have a void* "user data" parameter. You can pass a pointer to your class instance into "user data" of the "library function" and it will be forwarded into the callback where you can use that pointer to access the object.

class CallbackImplBase {
public:
   virtual void CallbackImpl() = 0;
   static void CallbackToPass( void* userData )
   {
       static_cast<CallbackImplBase*>(userData)->CallbackImpl();           
   }
};

class ActualCallbackImpl : public CallbackImplBase {
     void CallbackImpl() { //implemented here }
};

ActualCallbackImpl callback;
callLibraryFunction( params,
   &CallbackImplBase::CallbackToPass, static_cast<CallbackImplBase*>( &callback ) );

注意库函数"调用的最后一个参数附近的 static_cast.除非您有多重继承,否则您将不需要它,无论如何它仍然存在.

Note the static_cast near the last parameter of the "library function" call. You won't need it unless you have multiple inheritance, it's still there anyway.