C ++:静态函数包装器,路由到成员函数? [英] C++: static function wrapper that routes to member function?

查看:139
本文介绍了C ++:静态函数包装器,路由到成员函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过各种各样的设计方法来解决这个问题,但我似乎无法做到正确。

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

我需要暴露一些静态函数用作C库的回调函数。但是,我想实际的实现是非静态的,所以我可以使用虚函数和重用基类中的代码。如:

I need to expose some static functions to use as callback function to a C lib. However, I want the actual implementation to be non-static, so I can use virtual functions and reuse code in a base class. Such as:

class Callbacks {
  static void MyCallBack() { impl->MyCallBackImpl(); }
  ...

class CallbackImplBase {
   virtual void MyCallBackImpl() = 0;



< )我最终在一个死胡同(通常最终指向基类,而不是派生的)。

However I try to solve this (Singleton, composition by letting Callbacks be contained in the implementor class, etc) I end up in a dead-end (impl usually ends up pointing to the base class, not the derived one).

我不知道这是否可能,或者如果我坚持创建一些辅助函数而不是使用继承?

I wonder if it is at all possible or if I'm stuck with creating some sort of helper functions instead of using inheritance?

推荐答案

传递给回调函数的任何参数是否由用户定义?有什么方法可以将用户定义的值附加到传递给这些回调的数据?我记得当我实现Win32窗口的包装程序库我使用 SetWindowLong()这个指针附加到窗口句柄,该句柄以后可以在回调函数中检索。基本上,你需要将这个指针放在某处,这样当回调被触发时你可以检索它。

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();
}

这篇关于C ++:静态函数包装器,路由到成员函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆