c ++:当回调不提供用户arg时如何获取上下文? [英] c++: How to obtain context when callback doesn't provide user arg?

查看:68
本文介绍了c ++:当回调不提供用户arg时如何获取上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,请提供一些背景知识:

(注意:尽管我在非.NET Win32领域中,但这确实是C ++问题)

First, some background:
(Note: Though I'm in non-.NET Win32 land, this is really a C++ question)

我正在使用第三方API,该API要求您注册一个回调函数,以便了解异步操作何时完成。

I'm using a 3rd party API which requires you to register a callback function in order to know when an async operation is complete. Gotta use the callback, no way around it.

非OOP实现就是这样:

A non-OOP implementation would be something like this:

void __stdcall MyCbFcn(int value)
{
   do something with 'value'...
}

API_RegisterCallback(MyCbFcn);

非常标准的东西。

Pretty standard stuff.

BUT ...

我的代码是OOP,有多个实例接收回调,因此需要将回调路由到注册它的对象。

BUT...
My code is OOP, with multiple instances rx'ing the callback, thus the callback needs to be routed to the object that registered it.

知道人们会这样做,因此回调通常包括用户var,例如:

Knowing that folks do this, callbacks typically include a user var, something like:

void __stdcall MyCbFcn(int value, U32 user)
{
   do something with 'value'...
}

API_RegisterCallback(MyCbFcn, someUserValue);

更具体地说,当与OOP结合使用时,该用户arg允许您返回上下文: br />
(为简洁起见,以内联方式编写):

and more specifically, when combined with OOP, this user arg allows you to get back into context:
(written inline for brevity):

class MyClass
{
public:
   MyClass()
   {
      API_RegisterCallback(MyClass::StaticCbFcn, (U32)this);
   }

private:
   static void __stdcall StaticCbFcn(int value, U32 user)
   {
      MyClass* pThis = (MyClass*)user;
      pThis->InstanceCbFcn(value);
   }
   void InstanceCbFcn(int value)
   {
      ... do some work in context ...
   }
}

但是,我的API没有用户arg :(

BUT, my API doesn't feature a user arg :(

所以现在我的问题是:

如何回到上下文中?

So now my question:
How I can get back into context?

我已经考虑过一些粗略的事情,例如定义池 中创建了100个不同的回调并将它们分配为对象,但这似乎是一个真正的技巧。

I've considered kinda sketchy things like defining a "pool" of 100 distinct callbacks and assigning them as objects are created, but that seems like a real hack.

一个明显的解决方案...如果我在例如JavaScript :) ...将使用匿名函数,但是AFAIK C ++没有这样的东西。

An obvious solution ... if I were in e.g. JavaScript :) ... would be to use an anonymous function, but AFAIK C++ doesn't have anything like that.

任何想法都会受到赞赏。

Any ideas would be appreciated.

推荐答案

100个不同的回调实际上是唯一可以执行的操作,因此可以使用函数地址作为标识参数。

"100 distinct callbacks" is really the only thing you can do, thus you use the function address as identifying parameter. It might help to implement the different functions as template with a constant parameter:

template < unsinged N >
void StaticCbFcn( int value )
{
    map[ N ].InstanceCbFcn( value );
}

这篇关于c ++:当回调不提供用户arg时如何获取上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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