通过成员函数需要回调C接口 [英] Pass member function to C interface requiring callback

查看:101
本文介绍了通过成员函数需要回调C接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个旧的.dll与普通的C接口,需要回调时,一些工作做是为了调用。它需要回调的类型是无效(F *)(字符* ARG)

我在寻找一招,通过一个C ++函数对象有这么回调与存储在某个地方this指针,像绑定调用,而是简单绑定不起作用

要说明这一点:C接口:

 无效的typedef(F *)(字符*参数)回调;
无效registerCallback(回拨C);

在C ++用法:

  A级
{
    无效func1的()
    {
         registerCallback(性病::绑定(安培; A :: FUNC2,_1,这一点)); //明明好好尝试一下工作
    }    无效FUNC2(字符*参数)
    {...}
};


解决方案

这使这项工作有一个类的实例和类的成员函数,即我所知道的,唯一的办法是:


  1. 存放指向一个对象在一个全局变量。

  2. 注册一个非成员函数。

  3. 使用全局变量调用从非成员函数的成员函数。

  A级
{
    无效func1的();    无效FUNC2(字符*参数)
    {...}
};//全局指针
A * APTR = NULL;//非成员函数。
//为externC可能是需要的,如果旧的DLL期待
//一个重整的C函数指针。
为externC无效globalFunc2(字符*参数)
{
   如果(APTR == NULL)
   {
      //错误新政
   }
   其他
   {
      aPtr-> FUNC2(参数);
   }
}无效A :: func1的()
{
    APTR =这一点;
    registerCallback(globalFunc2);
}

I have an old .dll with plain C interface which takes callbacks to invoke when some work is done. The callback it takes is of type void (f*)(char* arg).

I'm looking for a trick to pass a C++ function object there so that the callback is invoked with "this" pointer stored somewhere, something like bind, but simple bind doesn't work

To illustrate this: C interface:

typedef void (f*)(char* param) Callback;
void registerCallback(Callback c);

Usage in C++:

class A
{
    void func1()
    {
         registerCallback(std::bind(&A::func2, _1, this)); // obviously doens't work
    }

    void func2(char* param)
    { ... }
};

解决方案

The only way that to make this work with an instance of a class and a member function of the class, that I am aware of, is:

  1. Store a pointer to an object in a global variable.
  2. Register a non-member function.
  3. Call the member function from the non-member function using the global variable.

class A
{
    void func1();

    void func2(char* param)
    { ... }
};

// Global pointer
A* aPtr = NULL;

// Non-member function.
// extern "C" is probably needed if the older DLL is expecting
// an unmangled C function pointer.
extern "C" void globalFunc2(char* param)
{
   if ( aPtr == NULL )
   {
      // Deal with error
   }
   else
   {
      aPtr->func2(param);
   }
}

void A::func1()
{
    aPtr = this;
    registerCallback(globalFunc2);
}

这篇关于通过成员函数需要回调C接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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