C++的注册和回调

注册回调的作用

  在设计模式中注册回调的方式叫做回调模式。在SDK开发中,为增强开发者的SDK通用性,排序或者一些算法逻辑需要使用者进行编写。这时候就需要向SDK传递回调函数。
注册回调能使下层主动与上层通信。从而避免了上层不停询问下层的模式。

注册回调的流程

  SDK的接口会提供一个注册回调函数,来规范回调函数的格式,如返回值,参数等。使用者编写一个固定格式的回调函数,来调用SDK提供的注册回调函数。当然,在c中注册回调的实现方式是通过函数指针,在c++中可以通过function和bind实现。

例1

  这是一个简单的函数调用,假设print()是sdk中的api,我们直接使用时候。

#include<iostream>
#include<cstdio>
using namespace std;
void print(string str);
//----------使用者模块-----------------
int main()
{
	print("hello word");
	system("pause");
	return 0;
}
//----------SDK模块-----------------
void print(string str)
{
	printf(str.c_str());
} 

例子2

  这次使用函数指针,来间接调用

#include<iostream>
#include<cstdio>
using namespace std;
void print(string str);
//----------使用者模块-----------------
int main()
{
	void(*p) (string str);
	p = print;
	p("hello word");
	system("pause");
	return 0;
}
//----------SDK模块-----------------
void print(string str)
{
	printf(str.c_str());
}

  

例子3

这就是一个简单的回调模式。sdk提供注册回调函数,使用者提供回调函数。

#include<iostream>
#include<cstdio>
using namespace std;
typedef void(*P)(string s);			//使用函数指针通常先typedef
P p = nullptr;						//sdk模块创建函数指针对象
void print(string str);				//使用者模块创建回调函数
void print_test(string, P p);		//注册回调函数
//----------使用者模块-----------------
int main()
{
	print_test("hello word", print);
	system("pause");
	return 0;
}
//----------回调函数----------
void print(string str)
{
	printf(str.c_str());
	printf("随便写");
}
//----------SDK模块-----------------
void print_test(string str, P prin)//注册回调函数
{
	p = prin;
	p(str);
}

  

例子4

  当然 在实际使用中,与上层通信的函数是常常放在一个线程循环中,等待事件响应,所以通信的函数是不能和注册函数写在一起,不能在通信函数中传入函数指针。需要单独注册。

//sdk.h
typedef void(*REC_CALLBACK)(long,char *,char *,char *);//调用函数格式
REC_CALLBACK record_callback;//创建实例
//.cpp
int register_callback(REC_CALLBACK P)//注册回调函数
{
	rec_callback = P;
	rec_callback_state = true;
	return 0;
}

init_record()
{
while(true)
{
  ..........
if (rec_callback1_state==true)
	{
		rec_callback(card, time, card_io, state);//调用回调函数
	}
else
	{
	}
}
}

  使用者模块

print(long,char *,char *,char *)//回调函数
{
   printf("xxxxx"long ,char......);
}

int main()
{
    register_callback(print)//使用前先注册
    std::thread t1(init_record);
    t1.join();

}

  

猜你喜欢

转载自www.cnblogs.com/wjcoding/p/11118421.html