首页 文章

c中的回调函数

提问于
浏览
233

在c中,何时以及如何使用回调函数?

EDIT:
我想看一个编写回调函数的简单示例 .

9 回答

  • 314

    回调函数是C标准的一部分,因此也是C的一部分 . 但如果您正在使用C,我建议您使用 observer pattern 代替:http://en.wikipedia.org/wiki/Observer_pattern

  • 0

    注意:大多数答案都涵盖了函数指针,这是在C中实现"callback"逻辑的一种可能性,但是到目前为止并不是我认为最有利的一种 .

    什么是回调(?)以及为什么要使用它们(!)

    回调是类或函数接受的可调用(参见下文),用于根据该回调自定义当前逻辑 .

    使用回调的一个原因是编写 generic 代码,该代码与被调用函数中的逻辑无关,并且可以与不同的回调一起使用 .

    标准算法库 <algorithm> 的许多功能都使用回调 . 例如, for_each 算法对一系列迭代器中的每个项应用一元回调:

    template<class InputIt, class UnaryFunction>
    UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
    {
      for (; first != last; ++first) {
        f(*first);
      }
      return f;
    }
    

    可以通过传递适当的callables来首先递增然后打印矢量,例如:

    std::vector<double> v{ 1.0, 2.2, 4.0, 5.5, 7.2 };
    double r = 4.0;
    std::for_each(v.begin(), v.end(), [&](double & v) { v += r; });
    std::for_each(v.begin(), v.end(), [](double v) { std::cout << v << " "; });
    

    打印

    5 6.2 8 9.5 11.2
    

    回调的另一个应用是向某些事件的调用者发出通知,这些事件启用了一定量的静态/编译时间灵活性 .

    就个人而言,我使用一个使用两个不同回调的本地优化库:

    • 如果需要函数值和基于输入值向量的梯度,则调用第一个回调(逻辑回调:函数值确定/梯度推导) .

    • 为每个算法步骤调用第二个回调,并接收有关算法收敛的某些信息(通知回调) .

    因此,库设计者不负责决定通过通知回调给予程序员的信息会发生什么,他不必担心如何实际确定函数值,因为它们是由逻辑回调提供的 . 由于库用户的原因,使这些事情正确是一项任务,并使库保持苗条和更通用 .

    此外,回调可以启用动态运行时行为 .

    想象一下某种游戏引擎类,它具有触发的功能,每次用户按下键盘上的按钮和一组控制游戏行为的功能 . 使用回调,您可以(重新)在运行时决定将采取哪些操作 .

    void player_jump();
    void player_crouch();
    
    class game_core
    {
        std::array<void(*)(), total_num_keys> actions;
        // 
        void key_pressed(unsigned key_id)
        {
            if(actions[key_id]) actions[key_id]();
        }
        // update keybind from menu
        void update_keybind(unsigned key_id, void(*new_action)())
        {
            actions[key_id] = new_action;
        }
    };
    

    这里函数 key_pressed 使用 actions 中存储的回调来获得按下某个键时所需的行为 . 如果玩家选择更改跳跃按钮,则引擎可以呼叫

    game_core_instance.update_keybind(newly_selected_key, &player_jump);
    

    因此,在下次游戏时按下此按钮后,将调用的行为更改为 key_pressed (调用 player_jump ) .

    C(11)中的可赎回物是什么?

    有关更正式的描述,请参阅cppreference上的C++ concepts: Callable .

    回调功能可以通过C(11)中的几种方式实现,因为几个不同的东西结果是 callable* :

    • 函数指针(包括指向成员函数的指针)

    • std::function 个对象

    • Lambda表达式

    • 绑定表达式

    • 函数对象(具有重载函数的类调用操作符 operator()

    *注意:指向数据成员的指针也是可调用的,但根本不调用任何函数 .

    详细编写回调的几种重要方法

    • X.1 "Writing"此帖子中的回调意味着声明和命名回调类型的语法 .

    • X.2 "Calling"回调是指调用这些对象的语法 .

    • X.3 "Using"回调是指使用回调将参数传递给函数时的语法 .

    注意:从C17开始,像 f(...) 这样的调用可以写成 std::invoke(f, ...) ,它也可以处理指向成员大小写的指针 .

    1.函数指针

    函数指针是回调可以具有的“最简单”(就通用性而言,可读性最差)类型 .

    让我们有一个简单的函数 foo

    int foo (int x) { return 2+x; }
    

    1.1编写函数指针/类型表示法

    function pointer type 有符号

    return_type (*)(parameter_type_1, parameter_type_2, parameter_type_3)
    // i.e. a pointer to foo has the type:
    int (*)(int)
    

    named function pointer 类型的样子

    return_type (* name) (parameter_type_1, parameter_type_2, parameter_type_3)
    
    // i.e. f_int_t is a type: function pointer taking one int argument, returning int
    typedef int (*f_int_t) (int); 
    
    // foo_p is a pointer to function taking int returning int
    // initialized by pointer to function foo taking int returning int
    int (* foo_p)(int) = &foo; 
    // can alternatively be written as 
    f_int_t foo_p = &foo;
    

    using 声明为我们提供了使事情更具可读性的选项,因为 typedef for f_int_t 也可以写成:

    using f_int_t = int(*)(int);
    

    哪里(至少对我而言)更清楚的是 f_int_t 是新类型别名并且对函数指针类型的识别也更容易

    并且 function using a callback of function pointer type 的声明将是:

    // foobar having a callback argument named moo of type 
    // pointer to function returning int taking int as its argument
    int foobar (int x, int (*moo)(int));
    // if f_int is the function pointer typedef from above we can also write foobar as:
    int foobar (int x, f_int_t moo);
    

    1.2回拨电话表示法

    电话符号遵循简单的函数调用语法:

    int foobar (int x, int (*moo)(int))
    {
        return x + moo(x); // function pointer moo called using argument x
    }
    // analog
    int foobar (int x, f_int_t moo)
    {
        return x + moo(x); // function pointer moo called using argument x
    }
    

    1.3回调使用符号和兼容类型

    可以使用函数指针调用带有函数指针的回调函数 .

    使用带函数指针回调的函数非常简单:

    int a = 5;
     int b = foobar(a, foo); // call foobar with pointer to foo as callback
     // can also be
     int b = foobar(a, &foo); // call foobar with pointer to foo as callback
    

    1.4示例

    可编写的函数不依赖于回调的工作方式:

    void tranform_every_int(int * v, unsigned n, int (*fp)(int))
    {
      for (unsigned i = 0; i < n; ++i)
      {
        v[i] = fp(v[i]);
      }
    }
    

    可能的回调可能是

    int double_int(int x) { return 2*x; }
    int square_int(int x) { return x*x; }
    

    用过像

    int a[5] = {1, 2, 3, 4, 5};
    tranform_every_int(&a[0], 5, double_int);
    // now a == {2, 4, 6, 8, 10};
    tranform_every_int(&a[0], 5, square_int);
    // now a == {4, 16, 36, 64, 100};
    

    2.指向成员函数的指针

    指向成员函数(某些类 C )的指针是一种特殊类型的(甚至更复杂的)函数指针,它需要一个 C 类型的对象来操作 .

    struct C
    {
        int y;
        int foo(int x) const { return x+y; }
    };
    

    2.1编写指向成员函数/类型表示法的指针

    pointer to member function type 对于某些类 T 有符号

    // can have more or less parameters
    return_type (T::*)(parameter_type_1, parameter_type_2, parameter_type_3)
    // i.e. a pointer to C::foo has the type
    int (C::*) (int)
    

    named pointer to member function 将-in类似于函数指针 - 如下所示:

    return_type (T::* name) (parameter_type_1, parameter_type_2, parameter_type_3)
    
    // i.e. a type `f_C_int` representing a pointer to member function of `C`
    // taking int returning int is:
    typedef int (C::* f_C_int_t) (int x); 
    
    // The type of C_foo_p is a pointer to member function of C taking int returning int
    // Its value is initialized by a pointer to foo of C
    int (C::* C_foo_p)(int) = &C::foo;
    // which can also be written using the typedef:
    f_C_int_t C_foo_p = &C::foo;
    

    示例:声明一个函数将 pointer to member function callback 作为其参数之一:

    // C_foobar having an argument named moo of type pointer to member function of C
    // where the callback returns int taking int as its argument
    // also needs an object of type c
    int C_foobar (int x, C const &c, int (C::*moo)(int));
    // can equivalently declared using the typedef above:
    int C_foobar (int x, C const &c, f_C_int_t moo);
    

    2.2回拨电话表示法

    通过对解除引用的指针使用成员访问操作,可以针对类型为 C 的对象调用指向 C 的成员函数的指针 . 注意:需要括号!

    int C_foobar (int x, C const &c, int (C::*moo)(int))
    {
        return x + (c.*moo)(x); // function pointer moo called for object c using argument x
    }
    // analog
    int C_foobar (int x, C const &c, f_C_int_t moo)
    {
        return x + (c.*moo)(x); // function pointer moo called for object c using argument x
    }
    

    注意:如果指向 C 的指针可用,则语法是等效的(其中指向 C 的指针也必须取消引用):

    int C_foobar_2 (int x, C const * c, int (C::*meow)(int))
    {
        if (!c) return x;
        // function pointer meow called for object *c using argument x
        return x + ((*c).*meow)(x); 
    }
    // or equivalent:
    int C_foobar_2 (int x, C const * c, int (C::*meow)(int))
    {
        if (!c) return x;
        // function pointer meow called for object *c using argument x
        return x + (c->*meow)(x); 
    }
    

    2.3回调使用符号和兼容类型

    可以使用类 T 的成员函数指针调用带有类 T 的成员函数指针的回调函数 .

    使用一个指向成员函数回调的函数是-in类似于函数指针 - 也很简单:

    C my_c{2}; // aggregate initialization
     int a = 5;
     int b = C_foobar(a, my_c, &C::foo); // call C_foobar with pointer to foo as its callback
    

    3. std :: function objects(header <functional>)

    std::function 类是用于存储,复制或调用callables的多态函数包装器 .

    3.1编写std :: function对象/类型表示法

    存储可调用对象的 std::function 对象的类型如下所示:

    std::function<return_type(parameter_type_1, parameter_type_2, parameter_type_3)>
    
    // i.e. using the above function declaration of foo:
    std::function<int(int)> stdf_foo = &foo;
    // or C::foo:
    std::function<int(const C&, int)> stdf_C_foo = &C::foo;
    

    3.2回拨电话表示法

    std::function 已定义 operator() ,可用于调用其目标 .

    int stdf_foobar (int x, std::function<int(int)> moo)
    {
        return x + moo(x); // std::function moo called
    }
    // or 
    int stdf_C_foobar (int x, C const &c, std::function<int(C const &, int)> moo)
    {
        return x + moo(c, x); // std::function moo called using c and x
    }
    

    3.3回调使用符号和兼容类型

    std::function 回调比函数指针或指向成员函数的指针更通用,因为可以传递不同的类型并将其隐式转换为 std::function 对象 .

    3.3.1 Function pointers and pointers to member functions

    一个函数指针

    int a = 2;
    int b = stdf_foobar(a, &foo);
    // b == 6 ( 2 + (2+2) )
    

    或指向成员函数的指针

    int a = 2;
    C my_c{7}; // aggregate initialization
    int b = stdf_C_foobar(a, c, &C::foo);
    // b == 11 == ( 2 + (7+2) )
    

    可以使用 .

    3.3.2 Lambda expressions

    来自lambda表达式的未命名闭包可以存储在 std::function 对象中:

    int a = 2;
    int c = 3;
    int b = stdf_foobar(a, [c](int x) -> int { return 7+c*x; });
    // b == 15 ==  a + (7*c*a) == 2 + (7+3*2)
    

    3.3.3 std::bind expressions

    可以传递 std::bind 表达式的结果 . 例如,通过将参数绑定到函数指针调用:

    int foo_2 (int x, int y) { return 9*x + y; }
    using std::placeholders::_1;
    
    int a = 2;
    int b = stdf_foobar(a, std::bind(foo_2, _1, 3));
    // b == 23 == 2 + ( 9*2 + 3 )
    int c = stdf_foobar(a, std::bind(foo_2, 5, _1));
    // c == 49 == 2 + ( 9*5 + 2 )
    

    其中对象也可以绑定为调用指向成员函数的指针的对象:

    int a = 2;
    C const my_c{7}; // aggregate initialization
    int b = stdf_foobar(a, std::bind(&C::foo, my_c, _1));
    // b == 1 == 2 + ( 2 + 7 )
    

    3.3.4 Function objects

    具有适当_1153209_重载的类的对象也可以存储在 std::function 对象中 .

    struct Meow
    {
      int y = 0;
      Meow(int y_) : y(y_) {}
      int operator()(int x) { return y * x; }
    };
    int a = 11;
    int b = stdf_foobar(a, Meow{8});
    // b == 99 == 11 + ( 8 * 11 )
    

    3.4示例

    更改函数指针示例以使用 std::function

    void stdf_tranform_every_int(int * v, unsigned n, std::function<int(int)> fp)
    {
      for (unsigned i = 0; i < n; ++i)
      {
        v[i] = fp(v[i]);
      }
    }
    

    为这个函数提供了更多的实用工具,因为(见3.3)我们有更多的可能性来使用它:

    // using function pointer still possible
    int a[5] = {1, 2, 3, 4, 5};
    stdf_tranform_every_int(&a[0], 5, double_int);
    // now a == {2, 4, 6, 8, 10};
    
    // use it without having to write another function by using a lambda
    stdf_tranform_every_int(&a[0], 5, [](int x) -> int { return x/2; });
    // now a == {1, 2, 3, 4, 5}; again
    
    // use std::bind :
    int nine_x_and_y (int x, int y) { return 9*x + y; }
    using std::placeholders::_1;
    // calls nine_x_and_y for every int in a with y being 4 every time
    stdf_tranform_every_int(&a[0], 5, std::bind(nine_x_and_y, _1, 4));
    // now a == {13, 22, 31, 40, 49};
    

    4.模板化回调类型

    使用模板,调用回调的代码可能比使用 std::function 对象更通用 .

    请注意,模板是编译时功能,是编译时多态的设计工具 . 如果要通过回调实现运行时动态行为,模板将有所帮助,但它们不会引发运行时动态 .

    4.1写入(类型表示法)并调用模板化回调

    通过使用模板可以进一步推广,即上面的 std_ftransform_every_int 代码:

    template<class R, class T>
    void stdf_transform_every_int_templ(int * v,
      unsigned const n, std::function<R(T)> fp)
    {
      for (unsigned i = 0; i < n; ++i)
      {
        v[i] = fp(v[i]);
      }
    }
    

    对于回调类型而言,更为通用(以及最简单)的语法是一个简单的,待推导的模板化参数:

    template<class F>
    void transform_every_int_templ(int * v, 
      unsigned const n, F f)
    {
      std::cout << "transform_every_int_templ<" 
        << type_name<F>() << ">\n";
      for (unsigned i = 0; i < n; ++i)
      {
        v[i] = f(v[i]);
      }
    }
    

    注意:包含的输出打印为模板类型 F 推导出的类型名称 . type_name 的实施在本文末尾给出 .

    范围的一元变换的最通用实现是标准库的一部分,即 std::transform ,其也是关于迭代类型的模板 .

    template<class InputIt, class OutputIt, class UnaryOperation>
    OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first,
      UnaryOperation unary_op)
    {
      while (first1 != last1) {
        *d_first++ = unary_op(*first1++);
      }
      return d_first;
    }
    

    4.2使用模板化回调和兼容类型的示例

    模板化 std::function 回调方法 stdf_transform_every_int_templ 的兼容类型与上面提到的相同类型(见3.4) .

    但是,使用模板化版本,使用的回调的签名可能会稍微改变:

    // Let
    int foo (int x) { return 2+x; }
    int muh (int const &x) { return 3+x; }
    int & woof (int &x) { x *= 4; return x; }
    
    int a[5] = {1, 2, 3, 4, 5};
    stdf_transform_every_int_templ<int,int>(&a[0], 5, &foo);
    // a == {3, 4, 5, 6, 7}
    stdf_transform_every_int_templ<int, int const &>(&a[0], 5, &muh);
    // a == {6, 7, 8, 9, 10}
    stdf_transform_every_int_templ<int, int &>(&a[0], 5, &woof);
    

    注意: std_ftransform_every_int (非模板化版本;见上文)适用于 foo 但不使用 muh .

    // Let
    void print_int(int * p, unsigned const n)
    {
      bool f{ true };
      for (unsigned i = 0; i < n; ++i)
      {
        std::cout << (f ? "" : " ") << p[i]; 
        f = false;
      }
      std::cout << "\n";
    }
    

    transform_every_int_templ 的普通模板化参数可以是每种可能的可调用类型 .

    int a[5] = { 1, 2, 3, 4, 5 };
    print_int(a, 5);
    transform_every_int_templ(&a[0], 5, foo);
    print_int(a, 5);
    transform_every_int_templ(&a[0], 5, muh);
    print_int(a, 5);
    transform_every_int_templ(&a[0], 5, woof);
    print_int(a, 5);
    transform_every_int_templ(&a[0], 5, [](int x) -> int { return x + x + x; });
    print_int(a, 5);
    transform_every_int_templ(&a[0], 5, Meow{ 4 });
    print_int(a, 5);
    using std::placeholders::_1;
    transform_every_int_templ(&a[0], 5, std::bind(foo_2, _1, 3));
    print_int(a, 5);
    transform_every_int_templ(&a[0], 5, std::function<int(int)>{&foo});
    print_int(a, 5);
    

    上面的代码打印:

    1 2 3 4 5
    transform_every_int_templ <int(*)(int)>
    3 4 5 6 7
    transform_every_int_templ <int(*)(int&)>
    6 8 10 12 14
    transform_every_int_templ <int& (*)(int&)>
    9 11 13 15 17
    transform_every_int_templ <main::{lambda(int)#1} >
    27 33 39 45 51
    transform_every_int_templ <Meow>
    108 132 156 180 204
    transform_every_int_templ <std::_Bind<int(*(std::_Placeholder<1>, int))(int, int)>>
    975 1191 1407 1623 1839
    transform_every_int_templ <std::function<int(int)>>
    977 1193 1409 1625 1841
    

    上面使用

    type_name实现

    #include <type_traits>
    #include <typeinfo>
    #include <string>
    #include <memory>
    #include <cxxabi.h>
    
    template <class T>
    std::string type_name()
    {
      typedef typename std::remove_reference<T>::type TR;
      std::unique_ptr<char, void(*)(void*)> own
        (abi::__cxa_demangle(typeid(TR).name(), nullptr,
        nullptr, nullptr), std::free);
      std::string r = own != nullptr?own.get():typeid(TR).name();
      if (std::is_const<TR>::value)
        r += " const";
      if (std::is_volatile<TR>::value)
        r += " volatile";
      if (std::is_lvalue_reference<T>::value)
        r += " &";
      else if (std::is_rvalue_reference<T>::value)
        r += " &&";
      return r;
    }
    
  • 146

    还有C方式做回调:函数指针

    //Define a type for the callback signature,
    //it is not necessary, but makes life easier
    
    //Function pointer called CallbackType that takes a float
    //and returns an int
    typedef int (*CallbackType)(float);  
    
    
    void DoWork(CallbackType callback)
    {
      float variable = 0.0f;
    
      //Do calculations
    
      //Call the callback with the variable, and retrieve the
      //result
      int result = callback(variable);
    
      //Do something with the result
    }
    
    int SomeCallback(float variable)
    {
      int result;
    
      //Interpret variable
    
      return result;
    }
    
    int main(int argc, char ** argv)
    {
      //Pass in SomeCallback to the DoWork
      DoWork(&SomeCallback);
    }
    

    现在,如果要将类方法作为回调传递,那些对这些函数指针的声明具有更复杂的声明,例如:

    //Declaration:
    typedef int (ClassName::*CallbackType)(float);
    
    //This method performs work using an object instance
    void DoWorkObject(CallbackType callback)
    {
      //Class instance to invoke it through
      ClassName objectInstance;
    
      //Invocation
      int result = (objectInstance.*callback)(1.0f);
    }
    
    //This method performs work using an object pointer
    void DoWorkPointer(CallbackType callback)
    {
      //Class pointer to invoke it through
      ClassName * pointerInstance;
    
      //Invocation
      int result = (pointerInstance->*callback)(1.0f);
    }
    
    int main(int argc, char ** argv)
    {
      //Pass in SomeCallback to the DoWork
      DoWorkObject(&ClassName::Method);
      DoWorkPointer(&ClassName::Method);
    }
    
  • 7

    Scott Meyers给出了一个很好的例子:

    class GameCharacter;
    int defaultHealthCalc(const GameCharacter& gc);
    
    class GameCharacter
    {
    public:
      typedef std::function<int (const GameCharacter&)> HealthCalcFunc;
    
      explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)
      : healthFunc(hcf)
      { }
    
      int healthValue() const { return healthFunc(*this); }
    
    private:
      HealthCalcFunc healthFunc;
    };
    

    我认为这个例子就说明了一切 .

    std::function<> 是编写C回调的"modern"方式 .

  • 9

    Callback function是一个传递给例程的方法,并在某个时刻被传递给它的例程调用 .

    这对于制作可重复使用的软件非常有用 . 例如,许多操作系统API(例如Windows API)大量使用回调 .

    例如,如果您想使用文件夹中的文件 - 您可以使用自己的例程调用API函数,并且您的例程将在指定文件夹中的每个文件中运行一次 . 这允许API非常灵活 .

  • 6

    接受的答案非常有用且非常全面 . 然而,OP表示

    我想看一个编写回调函数的简单示例 .

    所以在这里,从C11开始,你有 std::function 所以不需要函数指针和类似的东西:

    #include <functional>
    #include <string>
    #include <iostream>
    
    void print_hashes(std::function<int (const std::string&)> hash_calculator) {
        std::string strings_to_hash[] = {"you", "saved", "my", "day"};
        for(auto s : strings_to_hash)
            std::cout << s << ":" << hash_calculator(s) << std::endl;    
    }
    
    int main() {
        print_hashes( [](const std::string& str) {   /** lambda expression */
            int result = 0;
            for (int i = 0; i < str.length(); i++)
                result += pow(31, i) * str.at(i);
            return result;
        });
        return 0;
    }
    

    这个例子在某种程度上是真实的,因为你希望用不同的哈希函数实现来调用函数 print_hashes ,为此我提供了一个简单的例子 . 它接收一个字符串,返回一个int(提供的字符串的哈希值),你需要记住的所有语法部分是 std::function<int (const std::string&)> ,它描述了这样的函数作为将调用它的函数的输入参数 .

  • 4

    在C中没有明确的回调函数概念 . 回调机制通常通过函数指针,仿函数对象或回调对象来实现 . 程序员必须明确地设计和实现回调功能 .

    根据反馈进行修改:

    尽管这个答案得到了负面的反馈,但这并没有错 . 我会尝试更好地解释我来自哪里 .

    C和C具有实现回调函数所需的一切 . 实现回调函数的最常见和最简单的方法是将函数指针作为函数参数传递 .

    但是,回调函数和函数指针不是同义词 . 函数指针是一种语言机制,而回调函数是一种语义概念 . 函数指针不是实现回调函数的唯一方法 - 您还可以使用仿函数甚至花园种类的虚函数 . 使函数调用回调的原因不是用于标识和调用函数的机制,而是调用的上下文和语义 . 说某事是一个回调函数意味着调用函数和被调用的特定函数之间的分离大于正常,调用者和被调用者之间的概念耦合更松散,调用者可以明确控制被调用的内容 . 宽松的概念耦合和调用者驱动的函数选择的模糊概念使得某些东西成为回调函数,而不是使用函数指针 .

    例如,IFormatProvider的.NET文档说"GetFormat is a callback method",即使它只是一个普通的接口方法 . 我不会调用't think anyone would argue that all virtual method calls are callback functions. What makes GetFormat a callback method is not the mechanics of how it is passed or invoked, but the semantics of the caller picking which object'的GetFormat方法 .

    某些语言包含具有显式回调语义的功能,通常与事件和事件处理相关 . 例如,C#具有围绕回调概念明确设计的语法和语义的事件类型 . Visual Basic有它的Handles子句,它显式地声明一个方法作为回调函数,同时抽象出委托或函数指针的概念 . 在这些情况下,回调的语义概念被集成到语言本身中 .

    另一方面,C和C几乎没有明确地嵌入回调函数的语义概念 . 机制在那里,集成的语义不是 . 你可以很好地实现回调函数,但要获得更复杂的东西,包括你拥有的显式回调语义在C提供的基础上构建它,例如Qt对它们的Signals and Slots做了什么 .

    简而言之,C具有实现回调所需的功能,通常可以非常轻松地使用函数指针 . 它没有的是关键字和特征,其语义特定于回调,例如raise,emit,Handles,event =等 . 如果你来自具有这些类型元素的语言,C中的本机回调支持将感到绝望 .

  • 63

    请参阅上面的定义,其中声明回调函数被传递给某个其他函数,并且在某些时候它被调用 .

    在C中,希望让回调函数调用类方法 . 执行此操作时,您可以访问成员数据 . 如果使用C方式定义回调,则必须将其指向静态成员函数 . 这不是很理想 .

    以下是如何在C中使用回调 . 假设有4个文件 . 每个类的一对.CPP / .H文件 . C1类是带有我们想要回调的方法的类 . C2回调C1的方法 . 在这个例子中,回调函数有1个参数,我为读者添加了这个参数 . 该示例未显示实例化和使用的任何对象 . 此实现的一个用例是当您有一个类将数据读取并存储到临时空间时,另一个用于后处理数据 . 使用回调函数,对于读取的每一行数据,回调都可以处理它 . 这种技术可以减少所需临时空间的开销 . 它对返回大量数据的SQL查询特别有用,然后必须对其进行后处理 .

    /////////////////////////////////////////////////////////////////////
    // C1 H file
    
    class C1
    {
        public:
        C1() {};
        ~C1() {};
        void CALLBACK F1(int i);
    };
    
    /////////////////////////////////////////////////////////////////////
    // C1 CPP file
    
    void CALLBACK C1::F1(int i)
    {
    // Do stuff with C1, its methods and data, and even do stuff with the passed in parameter
    }
    
    /////////////////////////////////////////////////////////////////////
    // C2 H File
    
    class C1; // Forward declaration
    
    class C2
    {
        typedef void (CALLBACK C1::* pfnCallBack)(int i);
    public:
        C2() {};
        ~C2() {};
    
        void Fn(C1 * pThat,pfnCallBack pFn);
    };
    
    /////////////////////////////////////////////////////////////////////
    // C2 CPP File
    
    void C2::Fn(C1 * pThat,pfnCallBack pFn)
    {
        // Call a non-static method in C1
        int i = 1;
        (pThat->*pFn)(i);
    }
    
  • 37

    Boost的singals2允许您以线程安全的方式订阅通用成员函数(没有模板!) .

    示例:Document-View Signals可用于实现灵活的Document-View体系结构 . 该文档将包含每个视图可以连接的信号 . 以下Document类定义了一个支持多个视图的简单文本文档 . 请注意,它存储了所有视图将连接到的单个信号 .

    class Document
    {
    public:
        typedef boost::signals2::signal<void ()>  signal_t;
    
    public:
        Document()
        {}
    
        /* Connect a slot to the signal which will be emitted whenever
          text is appended to the document. */
        boost::signals2::connection connect(const signal_t::slot_type &subscriber)
        {
            return m_sig.connect(subscriber);
        }
    
        void append(const char* s)
        {
            m_text += s;
            m_sig();
        }
    
        const std::string& getText() const
        {
            return m_text;
        }
    
    private:
        signal_t    m_sig;
        std::string m_text;
    };
    

    接下来,我们可以开始定义视图 . 以下TextView类提供了文档文本的简单视图 .

    class TextView
    {
    public:
        TextView(Document& doc): m_document(doc)
        {
            m_connection = m_document.connect(boost::bind(&TextView::refresh, this));
        }
    
        ~TextView()
        {
            m_connection.disconnect();
        }
    
        void refresh() const
        {
            std::cout << "TextView: " << m_document.getText() << std::endl;
        }
    private:
        Document&               m_document;
        boost::signals2::connection  m_connection;
    };
    

相关问题