@[TOC]回调函数和函数指针
回调函数和函数指针
需求:某个工程,使用keil + c++98 做的,需要在单片机硬定时器里面回调一个函数
先申明一个包含回调函数指针的类:(注意 void (*Pcallback_function)();// 回调函数的指针)
class soft_timer_cell
{
public:
bool inited;//这个单元格被初始化过,可以使用
u16 evt_bit;
OS_TID evt_OS_TID;
void (*Pcallback_function)();// 回调函数的指针
soft_timer_cell (); //构造函数
// soft_timer_cell (); //构造函数
~soft_timer_cell (); //析构函数
void config (u32 period_mS,u16 evt_bit,OS_TID evt_OS_TID);
void config (u32 period_mS,void* Pcallback_function);
bool ontime_call();//返回true表示此次命中了
private:
u32 action;//==0无动作,==1在命中的时候发消息,==2是调用回调函数
std::auto_ptr<count_choice_n> ccn;
void init ();
};
//-----------------------------------------------------
void soft_timer_cell::init()
{
this->evt_bit=0;
this->evt_OS_TID=0;
this->Pcallback_function=NULL;
this->action=0;
this->inited=false;
}
//-----------------------------------------------------
void soft_timer_cell::config(u32 period_mS,void* Pcallback_function)
{
u32 k=period_mS/soft_timer_hardware_timer_period_mS;
k/=2;
this->ccn.reset(new count_choice_n(k));
//void (*this->Pcallback_function)(u32 count)=Pcallback_function;//语法错误,编译无法通过。
//(*this->Pcallback_function)(u32 count)=Pcallback_function;//语法错误,编译无法通过。
this->Pcallback_function =(void(*)()) Pcallback_function;
this->action=2;
this->inited=true;
}
注意 this->Pcallback_function =(void(*)()) Pcallback_function;这一行,给函数指针赋值
现在要在中断函数里面调用
bool soft_timer_cell::ontime_call()//这个函数可能在中断里面调用的
{
if(!this->inited)
return false;
else
{
if(this->ccn->ok())
{
switch(this->action)
{
case 0:
break;
case 1:
xxxxx此行省略;
break;
case 2:
//(*this->Pcallback_function)(this->ccn->count_ok); //语法错误,编译无法通过。调用回调函数
//(this->Pcallback_function)(this->ccn->count_ok); //语法错误,编译无法通过。调用回调函数
(*this->Pcallback_function)(); //调用回调函数
break;
default:
break;
};
return true;
}
else
return false;
}
}
这样就可以定时调用这个函数了
但是前面申明了soft_timer_cell::config(u32 period_mS,void* Pcallback_function) ,其实调用这个config还是很麻烦的,初始化代码如下
std::auto_ptr<Task_LED_evt> tle;
void tlee()
{
tle->flip_redLED(); //这里是回调函数真正执行的地方,就是翻转一个LED
}
void TL_init()
{
此处删除无关代码行;
void (*pt)() = tlee;
softTimer->append_a_timer(200,(void*)pt); //这里把指针强制转换成了void*,softTimer->append_a_timer里面调用了void soft_timer_cell::config(u32 period_mS,void* Pcallback_function)
}
以下是void soft_timer::append_a_timer的代码
void soft_timer::append_a_timer(u32 period_mS,void* Pcallback_function)//追加一个软定时器
{
for(u32 i=0;i<SOFT_TIMER_MAX_COUNT;i++)
{
bool a=this->stcs[i].inited;
if(!a)
{
this->stcs[i].config(period_mS,Pcallback_function);
return;
}
}
}
看懂了吗,我折腾了好几个小时搞出来的