Implementing callback (for C library) as pure virtual in C++ abstract class

后端 未结 2 1803
滥情空心
滥情空心 2021-01-25 17:38

I ran into a problem when using a C audio library (PortAudio built with ASIO SDK, but this isn\'t really relevant to this question; the technical details would only hinder m

2条回答
  •  情书的邮戳
    2021-01-25 18:04

    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(userData)->CallbackImpl();           
       }
    };
    
    class ActualCallbackImpl : public CallbackImplBase {
         void CallbackImpl() { //implemented here }
    };
    
    ActualCallbackImpl callback;
    callLibraryFunction( params,
       &CallbackImplBase::CallbackToPass, static_cast( &callback ) );
    

    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.

提交回复
热议问题