NS3的Callback例子讲解
程序员文章站
2022-07-06 13:20:06
...
以ns-3.25/ex1/examples下面的main-callback.cc为例,讲解Callback用法。
#include "ns3/callback.h"
#include "ns3/assert.h"
#include <iostream>
using namespace ns3;
static double
CbOne (double a, double b)
{
std::cout << "invoke cbOne a=" << a << ", b=" << b << std::endl;
return a;
}
/** Example Callback class. */
class MyCb {
public:
/**
* Example Callback class method.
*
* \param [in] a The argument.
* \returns -5
*/
int CbTwo (double a) {
std::cout << "invoke cbTwo a=" << a << std::endl;
return -5;
}
};
int main (int argc, char *argv[])
{
// return type: double
// first arg type: double
// second arg type: double
Callback<double, double, double> one;
// build callback instance which points to cbOne function
one = MakeCallback (&CbOne);
// this is not a null callback
NS_ASSERT (!one.IsNull ());
// invoke cbOne function through callback instance
double retOne;
retOne = one (10.0, 20.0);
// callback returned expected value
NS_ASSERT (retOne == 10.0);
// return type: int
// first arg type: double
Callback<int, double> two;
MyCb cb;
// build callback instance which points to MyCb::cbTwo
two = MakeCallback (&MyCb::CbTwo, &cb);
// this is not a null callback
NS_ASSERT (!two.IsNull ());
// invoke MyCb::cbTwo through callback instance
int retTwo;
retTwo = two (10.0);
// callback returned expected value
NS_ASSERT (retTwo == -5);
two = MakeNullCallback<int, double> ();
// invoking a null callback is just like
// invoking a null function pointer:
// it will crash.
//int retTwoNull = two (20.0);
NS_ASSERT (two.IsNull ());
#if 0
// The below type mismatch between CbOne() and callback two will fail to
// compile if enabled in this program.
two = MakeCallback (&CbOne);
#endif
#if 0
// This is a slightly different example, in which the code will compile
// but because callbacks are type-safe, will cause a fatal error at runtime
// (the difference here is that Assign() is called instead of operator=)
Callback<void, float> three;
three.Assign (MakeCallback (&CbOne));
#endif
return 0;
}
首先我们观察到第一个Callback与Cbone有这样的关系:
如果这个函数和Callback函数有相同的函数参数类型,那么我们可以把这个函数绑定为Callback函数。Callback函数第一个参数是返回类型,后边的是参数类型。
Callback只是一个声明的作用,它表示我们绑定任意符合要求的函数到Callback函数,那么我们究竟要绑定哪个函数呢?接下来我们用MakeCallback函数绑定到具体的函数上去。
// build callback instance which points to cbOne function
one = MakeCallback (&CbOne);
接下来:
NS_ASSERT (!one.IsNull ());
这句话为了保证Callback为非空,也就是说,Callback绑定到了特定的函数。
第二次调用Callback函数,是绑定到了类的成员函数上,原理一样。
我们可以看一下Callback函数和MakeCallback原型
参数:
memPtr Class method member pointer
objPtr Class instance
返回:
A wrapper Callback