C++: static function wrapper that routes to member function?

前端 未结 4 436
北荒
北荒 2021-01-14 05:45

I\'ve tried all sorts of design approaches to solve this problem, but I just can\'t seem to get it right.

I need to expose some static functions to use as callback f

4条回答
  •  误落风尘
    2021-01-14 06:33

    Are any of the parameters passed to the callback function user defined? Is there any way you can attach a user defined value to data passed to these callbacks? I remember when I implemented a wrapper library for Win32 windows I used SetWindowLong() to attach a this pointer to the window handle which could be later retrieved in the callback function. Basically, you need to pack the this pointer somewhere so that you can retrieve it when the callback gets fired.

    struct CALLBACKDATA
    {
      int field0;
      int field1;
      int field2;
    };
    
    struct MYCALLBACKDATA : public CALLBACKDATA
    {
      Callback* ptr;
    };
    
    
    registerCallback( Callback::StaticCallbackFunc, &myCallbackData, ... );
    
    void Callback::StaticCallbackFunc( CALLBACKDATA* pData )
    {
      MYCALLBACKDATA* pMyData = (MYCALLBACKDATA*)pData;
      Callback* pCallback = pMyData->ptr;
    
      pCallback->virtualFunctionCall();
    }
    

提交回复
热议问题