C语言回调函数
Callbacks have a wide variety of uses. For example, imagine a function that reads a configuration file and associates values with options. If the options are identified by a hash, then writing the function so that it takes a callback makes it more flexible: its user can choose whatever hashing algorithm is desired and the function will continue to work, since it uses the callback to turn option names into hashes; thus, callbacks allow the user of a function to fine-tune it at runtime. Another use is in error signaling. A Unix program, for example, might not want to terminate immediately when it receives SIGTERM; to make sure things get taken care of, it would register the cleanup function as a callback.
Callbacks may also be used to control whether a function acts or not: Xlib allows custom predicates to be specified to determine whether a program wishes to handle an event. The following code in C demonstrates the use of callbacks to display two numbers.
#include <stdio.h>
#include <stdlib.h> /* The calling function takes a single callback as a parameter. */
void PrintTwoNumbers(int (*numberSource)(void)) {
printf("%d and %d\n", numberSource(), numberSource());
} /* A possible callback */
int overNineThousand(void) {
return (rand() % ) + ;
} /* Another possible callback. */
int meaningOfLife(void) {
return ;
} /* Here we call PrintTwoNumbers() with three different callbacks. */
int main(void) {
PrintTwoNumbers(&rand);
PrintTwoNumbers(&overNineThousand);
PrintTwoNumbers(&meaningOfLife);
return ;
}
This should provide output similar to:
125185 and 89187225
9084 and 9441
42 and 42
Note how this is different from simply passing the output of the callback function to the calling function, PrintTwoNumbers() - rather than printing the same value twice, the PrintTwoNumbers calls the callback as many times as it requires. This is one of the two main advantages of callbacks.
The other advantage is that the calling function can pass whatever parameters it wishes to the called functions (not shown in the above example). This allows correct information hiding: the code that passes a callback to a calling function does not need to know the parameter values that will be passed to the function. If it only passed the return value, then the parameters would need to be exposed publicly.[examples needed]
Another example:
/*
* This is a simple C program to demonstrate the usage of callbacks
* The callback function is in the same file as the calling code.
* The callback function can later be put into external library like
* e.g. a shared object to increase flexibility.
*
*/ #include <stdio.h>
#include <string.h>
#include <stdlib.h> typedef struct _MyMsg {
int appId;
char msgbody[];
} MyMsg; void myfunc(MyMsg *msg)
{
if (strlen(msg->msgbody) > )
printf("App Id = %d \n Msg = %s \n",msg->appId, msg->msgbody);
else
printf("App Id = %d \n Msg = No Msg\n",msg->appId);
} /*
* Prototype declaration
*/
void (*callback)(void *); int main(void)
{
MyMsg msg1;
msg1.appId = ;
strcpy(msg1.msgbody, "This is a test\n"); /*
* Assign the address of the function 'myfunc' to the function
* pointer 'callback'
*/
callback = (void *)myfunc; /*
* Call the function
*/
callback((MyMsg*)&msg1); return ;
}
The output after compilation:
$ gcc cbtest.c
$ ./a.out
App Id = 100
Msg = This is a test
C语言回调函数的更多相关文章
- C语言回调函数详解
1. 什么是回调函数? 回调函数,光听名字就比普通函数要高大上一些,那到底什么是回调函数呢?恕我读得书少,没有在那本书上看到关于回调函数的定义.我在百度上搜了一下,发现众说纷纭,有很大一部分都是使用类 ...
- 转·带你用实例理解C语言回调函数
原文出处:https://segmentfault.com/a/1190000008293902?utm_source=tag-newest 前言: 如不懂函数指针,请先查阅关于函数指针内容的资料(h ...
- 【转】一文搞懂C语言回调函数
转:https://segmentfault.com/a/1190000008293902?utm_source=tag-newest 什么是回调函数 我们先来看看百度百科是如何定义回调函数的: 回调 ...
- 对c语言回调函数的理解
对于回调函数,可以简单的理解为一种特别的函数调用方法,我们可以对比一下回调函数与普通函数在调用方法上的区别. 1. 普通函数调用 一般为实现方在其函数体执行过程中直接调用. 代码示例: #includ ...
- C语言回调函数总结
/* Main program ---calls--> Library function ---calls--> Callback funtion */ #include <stdi ...
- C语言中的回调函数(Callback Function)
1 定义和使用场合 回调函数是指 使用者自己定义一个函数,实现这个函数的程序内容,然后把这个函数(入口地址)作为参数传入别人(或系统)的函数中,由别人(或系统)的函数在运行时来调用的函数.函数是你实现 ...
- C语言的本质(17)——回调函数
如果函数的参数是一个函数指针,我们可以通过这个函数指针传递一个函数的地址给另外一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数(Callback Function).回调函数不是由 ...
- C语言中的回调函数
C语言中通过函数指针实现回调函数(Callback Function) ====== 首先使用typedef定义回调函数类型 ====== typedef void (*event_cb_t)(co ...
- C语言学习及应用笔记之七:C语言中的回调函数及使用方式
我们在使用C语言实现相对复杂的软件开发时,经常会碰到使用回调函数的问题.但是回调函数的理解和使用却不是一件简单的事,在本篇我们根据我们个人的理解和应用经验对回调函数做简要的分析. 1.什么是回调函数 ...
随机推荐
- [MetaHook] R_SparkEffect
By hzqst void R_SparkEffect(float *pos, int count, int velocityMin, int velocityMax) { efx.R_SparkSt ...
- Opencv step by step - 阈值化
Opencv里面的阈值化做起来比较简单,只需要一个函数即可: /* Applies fixed-level threshold to grayscale image. This is a basic ...
- win8安装mean.io详解
最近,老大说要安装mean.io,然后……我的win8华丽丽的就上战场了……这期间真是安装得要生要死……最终也终于“不辱使命”成功安装上了…… 废话不多说,进入正题啦 前提当然是电脑有node.环境… ...
- [wikioi2069]油画(贪心)
题目:http://www.wikioi.com/problem/2069/ 分析: 首先这个问题比较复杂,涉及到两个重要的考虑点,一个是当前拿来的颜色是否保留,一个是若保留后那么应该把当前盘子的哪个 ...
- [USACO2005][poj2229]Sumsets(递推)
http://poj.org/problem?id=2229 分析: 显然的递推 若n为奇数,那么肯定是在n-1的基础上前面每个数+1,即f[n]=f[n-1] 若n为偶数 当第一位数字是1的时候,等 ...
- 【Groovy基础系列】 Groovy运算符
?运算符 在java中,有时候为了避免出现空指针异常,我们通常需要这样的技巧: if(rs!=null){ rs.next() … … } 在groovy中,可以使用?操作符达到同样的目的: rs?. ...
- iOS UI基础-17.0 UILable之NSMutableAttributedString
在iOS开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求.之前在网上找了一些资料,有的是重绘UILabel的textLayer,有的是用html5实现的,都比较麻烦 ...
- [转]Oracle数据库中的约束
SQL 约束 约束用于限制加入表的数据的类型. 可以在创建表时规定约束(通过 CREATE TABLE 语句),或者在表创建之后也可以(通过 ALTER TABLE 语句). 我们将主要探讨以下几种约 ...
- Java-set
set public interface Set<E> extends Collection<E> 使用集合汇总 package 集合类.Set类; /** * Set不允许重 ...
- 如何查询Oracle中用户所有信息
1.查看所有用户: select * from dba_users; select * from all_users; select * from user_users; 2. ...