当前位置:网站首页>C language callback function [C language]
C language callback function [C language]
2022-07-06 11:58:00 【Weiyuan escort agency】
What is a callback function
Let's take a look at how Baidu Encyclopedia defines callback functions :
A callback function is a function called through a function pointer . If you put a pointer to a function ( Address ) Pass as argument to another function , When this pointer is used to call the function it points to , Let's just say this is a callback function . The callback function is not called directly by the function's implementer , It's called by another party when a particular event or condition occurs , Used to respond to the event or condition .
This passage is quite long , Also more tongue twister . Next, I will illustrate what callback is through a figure :

Suppose we want to use a sort function to sort the array , Then in the main program (Main program) in , Let's go through the library first , Select a library sort function (Library function). But there are many sorting algorithms , There's bubble sort , Selection sort , Quick sort , Merge sort . meanwhile , We may also need to sort special objects , Such as specific structures . The library function will choose a sort algorithm according to our needs , Then call the function that implements the algorithm to complete the sorting . The called sorting function is the callback function (Callback function).
Combine this picture with the above explanation of callback function , We can find out , To implement a callback function , The key point is to pass the pointer of a function to a function ( The above figure shows the library function ), Then the function can call the callback function through this pointer . Be careful , The callback function is not C Language specific , Almost any language has callback functions . stay C In language , We implement the callback function by using the function pointer . What is the function pointer ? take it easy , Now let's take a look at what is a function pointer .
What is a function pointer
Function pointers are also pointers , It just doesn't point to an integer , Character type, but function . stay C in , Each function is stored in memory after compilation , And each function has an entry address , According to this address , We can access and use this function . The function pointer points to the entry of this function , To call this function .
The use of function pointers
Definition of function pointer
Although the function pointer is also a pointer , But it is defined in a way that looks very different from other pointers , Let's see how it is defined :
/* Method 1 */
void (*p_func)(int, int, float) = NULL;
/* Method 2 */
typedef void (*tp_func)(int, int, float);
tp_func p_func = NULL; Both methods define a point whose return value is void type , Parameter is (int, int, float) Function pointer of . The second method is to make the function pointer easier to understand , Especially in complex environments ; For general function pointers , Just use the first method .
If you haven't seen function pointers before , You may find the definition of function pointer strange , Why not void ()(int, int, float) *p_func It is void (*p_func)(int, int, float) This form ? I don't know this question , There's no need to tangle , Take a moment to understand the difference between it and ordinary pointers , If you can't, just remember its form first .
Assignment of function pointer
After defining the function pointer , We need to assign a value to it. We have two ways to assign a value to a function pointer :
void (*p_func)(int, int, float) = NULL;
p_func = &func1;
p_func = func2; Both of the above methods are legal , For the second method , The compiler implicitly converts func_2 from void ()(int, int, float) Type conversion to void (*)(int, int, float) type , therefore , Both methods work . For more detailed instructions , Take a look at the following stackoverflow Of link .
Call a function... Using a function pointer
Because function pointers are also pointers , Therefore, a conventional belt can be used * Method to call the function . The same as the assignment of function pointer , We can also use two methods :
/* Method 1 */
int val1 = p_func(1,2,3.0);
/* Method 2 */
int val2 = (*p_func)(1,2,3.0); Method 1 It's the same as we usually call functions directly , Method 2 It's used * Value the function pointer , So as to realize the call to the function .
Pass the function pointer as an argument to the function
Function pointers are the same as ordinary pointers , We can pass it to the function as a parameter of the function , Now let's see how to realize the parameter passing of function pointer :
/* func3 Put the function pointer p_func As its formal parameter */
void func3(int a, int b, float c, void (*p_func)(int, int, float))
{
(*p_func)(a, b, c);
}
/* func4 Call function func3 */
void func4()
{
func3(1, 2, 3.0, func_1);
/* perhaps func3(1, 2, 3.0, &func_1); */
}Function pointer as function return type
With the above foundation , It should not be difficult to write a function whose return type is a function pointer , The following example is a function whose return type is a function pointer :
void (* func5(int, int, float ))(int, int)
{
...
} ad locum , func5 With (int, int, float) Is the parameter , Its return type is void (*)(int, int) . stay C In language , The declaration of variables or functions is also a big learning , Want to know more about the topic of declaration , Please refer to my previous articles - C Experts programming 》 Reading notes (1-3 Chapter ). The third chapter of this book spends a whole chapter explaining how to read C Declaration of language .
Function pointer array
Before we start talking about callback functions , Finally, let's introduce the function pointer array . Since the function pointer is also a pointer , Then we can use arrays to store function pointers . Let's take a look at an example of a function pointer array :
/* Method 1 */
void (*func_array_1[5])(int, int, float);
/* Method 2 */
typedef void (*p_func_array)(int, int, float);
p_func_array func_array_2[5]; Both of the above methods can be used to define the function pointer array , They define a number of elements as 5, The type is void (*)(int, int, float) An array of function pointers for .
Callback function
What we talked about earlier is function pointers , Let's get back to the point , Let's see how the callback function is implemented . The following is a simple callback function example of four operations :
#include <stdio.h>
#include <stdlib.h>
/****************************************
* Function pointer structure
***************************************/
typedef struct _OP {
float (*p_add)(float, float);
float (*p_sub)(float, float);
float (*p_mul)(float, float);
float (*p_div)(float, float);
} OP;
/****************************************
* Addition, subtraction, multiplication and division function
***************************************/
float ADD(float a, float b)
{
return a + b;
}
float SUB(float a, float b)
{
return a - b;
}
float MUL(float a, float b)
{
return a * b;
}
float DIV(float a, float b)
{
return a / b;
}
/****************************************
* Initialize function pointer
***************************************/
void init_op(OP *op)
{
op->p_add = ADD;
op->p_sub = SUB;
op->p_mul = &MUL;
op->p_div = &DIV;
}
/****************************************
* Library function
***************************************/
float add_sub_mul_div(float a, float b, float (*op_func)(float, float))
{
return (*op_func)(a, b);
}
int main(int argc, char *argv[])
{
OP *op = (OP *)malloc(sizeof(OP));
init_op(op);
/* Call a function directly using a function pointer */
printf("ADD = %f, SUB = %f, MUL = %f, DIV = %f\n", (op->p_add)(1.3, 2.2), (*op->p_sub)(1.3, 2.2),
(op->p_mul)(1.3, 2.2), (*op->p_div)(1.3, 2.2));
/* Call callback function */
printf("ADD = %f, SUB = %f, MUL = %f, DIV = %f\n",
add_sub_mul_div(1.3, 2.2, ADD),
add_sub_mul_div(1.3, 2.2, SUB),
add_sub_mul_div(1.3, 2.2, MUL),
add_sub_mul_div(1.3, 2.2, DIV));
return 0;
}This example is a little long , I explain step by step how to use callback functions .
First step
To complete addition, subtraction, multiplication and division , We need to define four functions to realize the operation of addition, subtraction, multiplication and division , These functions are :
/****************************************
* Addition, subtraction, multiplication and division function
***************************************/
float ADD(float a, float b)
{
return a + b;
}
float SUB(float a, float b)
{
return a - b;
}
float MUL(float a, float b)
{
return a * b;
}
float DIV(float a, float b)
{
return a / b;
}The second step
We need to define four function pointers to these four functions :
/****************************************
* Function pointer structure
***************************************/
typedef struct _OP {
float (*p_add)(float, float);
float (*p_sub)(float, float);
float (*p_mul)(float, float);
float (*p_div)(float, float);
} OP;
/****************************************
* Initialize function pointer
***************************************/
void init_op(OP *op)
{
op->p_add = ADD;
op->p_sub = SUB;
op->p_mul = &MUL;
op->p_div = &DIV;
}The third step
We need to create one “ Library function ”, This function takes the function pointer as an argument , Use it to call different functions :
/****************************************
* Library function
***************************************/
float add_sub_mul_div(float a, float b, float (*op_func)(float, float))
{
return (*op_func)(a, b);
}Step four
When these films are finished , We can call the callback function :
/* Call callback function */
printf("ADD = %f, SUB = %f, MUL = %f, DIV = %f\n",
add_sub_mul_div(1.3, 2.2, op->p_add),
add_sub_mul_div(1.3, 2.2, op->p_sub),
add_sub_mul_div(1.3, 2.2, MUL),
add_sub_mul_div(1.3, 2.2, DIV));The callback function can be implemented in four simple parts . In these four steps , We can even omit the second step , Pass the function name directly into “ Library function ”, For example, the above multiplication and division operations . The core of the callback function is the function pointer , As long as you understand the function pointer, you can learn the callback function , That's easy to catch .
summary
This article mainly talks about how to use function pointers and callback functions . The core of the callback function is the function pointer , So I spent a lot of time explaining function pointers . For the implementation of callback function , I gave an example , I hope this example can help you . Callback function is very important , If you can't even do it ,C Language is really not a beginner . Yes, of course , Even if I can do it , Don't be proud , because C There are still too many things we need to learn about language 、 practice .
If you find this helpful , Please praise and support , thank you !
边栏推荐
- 2019腾讯暑期实习生正式笔试
- L2-004 is this a binary search tree? (25 points)
- 機器學習--線性回歸(sklearn)
- [Flink] Flink learning
- Comparison of solutions of Qualcomm & MTK & Kirin mobile platform USB3.0
- 2020网鼎杯_朱雀组_Web_nmap
- L2-001 emergency rescue (25 points)
- Gallery之图片浏览、组件学习
- Connexion sans mot de passe du noeud distribué
- B tree and b+ tree of MySQL index implementation
猜你喜欢
随机推荐
[Flink] Flink learning
机器学习--决策树(sklearn)
C语言回调函数【C语言】
error C4996: ‘strcpy‘: This function or variable may be unsafe. Consider using strcpy_ s instead
Vert. x: A simple TCP client and server demo
Gallery's image browsing and component learning
wangeditor富文本引用、表格使用问题
分布式節點免密登錄
Password free login of distributed nodes
Principle and implementation of MySQL master-slave replication
Internet protocol details
E-commerce data analysis -- User Behavior Analysis
arduino UNO R3的寄存器写法(1)-----引脚电平状态变化
2019腾讯暑期实习生正式笔试
互聯網協議詳解
Those commonly used tool classes and methods in hutool
arduino获取随机数
Word排版(小計)
Basic use of pytest
Wangeditor rich text component - copy available









