c的注册和回调浅谈

注册回调的作用

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

注册回调的流程

SDK的接口会提供一个注册回调函数,来规范回调函数的格式,如返回值,参数等。
使用者编写一个固定格式的回调函数,来调用SDK提供的注册回调函数。

当然,在c中注册回调的实现方式是通过函数指针,在c++中可以通过function和bind实现。

栗子

从最基本的基础,开始了解注册和回调,也可以直接看栗子4。

栗子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(P p, string);
//----------使用者模块-----------------
int main()
{
	print_test(print, "hello word");
	system("pause");
	return 0;
}

void print(string str)//回调函数
{
	printf(str.c_str());
	printf("随便写");
}
//----------SDK模块-----------------
void print_test(P prin, string str)//注册回调函数
{
    p=prin;
	p(str);
}

栗子4

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

sdk模块

//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();

}
  • 6
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

工农村贴膜小哥

我倒是要看看是那个憨憨在给我打

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值