将非静态成员函数作为回调传递

时间:2017-05-02 17:34:39

标签: c++ c++11 callback

我发现了几个类似的问题,但解决方案并不适合我的情况。 在C ++方法中,我调用一个C api,它将回调作为其参数之一。

class A
{

   herr_t methodA(some parameters) {....}

   void methodB(some parameters)
   {
       ....

       int status =  CAPI(other parameters, callback, last parameter);
   }

};

CAPI的原型是

herr_t CAPI( some parameters, H5L_iterate_t op, other parameters);

H5L_iterate_t由

定义
herr_t (*H5L_iterate_t)( hid_t g_id, const char *name, 
                         const H5L_info_t *info, void *op_data) 

方法A与H5L_iterate_t具有相同的签名 在methodB中,

status = CAPI(..., **(H5L_iterate_t )std::bind(&A::methodA, this,
              std::placeholders::_1)**, ...);

我得到的编译错误是"无法从...转换为H5L_iterate_t"。我想知道将非静态成员函数作为回调传递的正确方法是什么。

提前致谢。

1 个答案:

答案 0 :(得分:2)

提供回调的C API几乎总是遵循这种模式:

extern "C"
{
    typedef void(*callback_function)(void* data);    

    typedef int handle_type;

    void do_something_with_callback(handle_type, callback_function, void *data);
}

在调用data时,无论你传递的do_something_with_callback参数是什么,都会被传递给callback_function

您可以使用此用户数据传递指向c ++对象地址的指针,然后您可以将其转换回指向对象类型的指针:

struct my_object
{
    void initiate()
    {
        // call the C interface, passing our c-style callback function with
        // a pointer to this class as the user data
        do_something_with_callback(handle_, &callback_launch_function, this);
    }

private:
    static void callback_launch_function(void * data) {
        // the data will always be a pointer to my_object - 
        // because that's what we passed.
        auto self = reinterpret_cast<my_object*>(data);
        self->handle_it();
    }

    // this is our c++style callback
    void handle_it()
    {

    }

    handle_type handle_;
};
相关问题