C语言中应用回调函数的地方非常多,如Nginx中:
struct ngx_command_s {
ngx_str_t name;
ngx_uint_t type;
char *(*set)(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
ngx_uint_t conf;
ngx_uint_t offset;
void *post;
};
ngx_command_s结构体存的是命令的值,其中成员 set 是一个回调函数指针,指向设置函数值的回调函数,用于设置命令的值。
回调函数是使用函数指针实现的。再比如C语言标准库stdlib中的快速排序函数qsort():
void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );
其中,comparator是一个函数指针,指向的是我们自己实现的比较函数,这是一个回调函数。在使用qsort时,需要传入比较函数的指针作为参数(注意:函数名实际上就是函数的指针)。
More…………………
提到函数指针,顺便说一说函数指针数组。
假如要实现一个计算器,包括加、减、乘、除四种运算,每个运算对应一个函数。我们可以实现switch case数组来判断操作。如:
switch (oper)
{
case ADD:
result = add(op1, op2);
break;
case SUB:
result = sub(op1, op2);
break;
case MUL:
result = mul(op1, op2);
break;
case DIV:
result = div(op1, op2);
break;
}
这样一来显得很麻烦,我们可以使用函数指针数组来简化。
首先,声明操作函数原型。
然后,声明函数指针数组:
double (*oper_func[])(double, double)={
add,sub,mul,div
}
最后,我们可以用一条语句替换switch case结构:
result = oper_func[oper](op1, op2);