Linux下C语言可变参数的回调函数
发布时间:2022-11-29 14:37:21 285 相关标签:
摘要
函数指针 可变宏 注册回调函数 调用回调函数
前言
这是一个小代码片, 这种类型的函数指针一般应该是打印日志,按格式写东西用的。因此这里的源码部分提供的是可变参数的第一个为一个只读字符串格式。
假如是可变参数的第一个带入的是个数的话,
typedef char byte;
/*定义函数指针类型*/
typedef int(*pf_put)(const int cnt,...);
void write_byte(const int cnt,...)
{
va_list args;//char*args;
va_start(args,cnt);//(args=(va_list)(&cnt)+_INTSIZEOF(cnt));
int i=0;
for(;i<cnt;i++)
{
//注释的提升到int
byte t=va_arg(args,int);//char:int
printf("%c\n",t);
}
va_end(args);//(args=(va_list)0);
}
许多开源的C项目中会用到注册回调函数,信号注册函数也是类似,只是参数是固定的。
源码
/*
compile:gcc a.c
run:./a.out
*/
#include
#include
#include
/*可变宏,直接调用的,本程序中未使用*/
#define P_WRITE(format,...) hhw(format,##__VA_ARGS__)
/*定义函数指针类型*/
typedef int(*pf_put)(const char*format,...);
/*具体实现的函数体*/
int hhw(const char*formt,...)
{
va_list ap;
int ret;
va_start(ap,formt);
ret=vprintf(formt,ap);
va_end(ap);
return ret;
}
void register_p(pf_put *a)
{
(*a)=hhw;
}
void callback_done(pf_put a)
{
a("%s %d\n","test",5);
}
int main(){
pf_put mycall=NULL;
register_p(&mycall);
callback_done(mycall);
return 0;
}
文章来源: https://blog.51cto.com/datrilla/5885661
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报