作业3:深入理解Callback函数

吖!查無此人 2023-04-03 12:27:16

一、callback函数

回调函数就是一个通过函数指针调用的函数。如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,我们就说这是回调函数。回调函数不是由该函数的实现方直接调用,而是在特定的事件或条件发生时由另外的一方调用的,用于对该事件或条件进行响应。 
回调函数机制: 
1、定义一个函数(普通函数即可); 
2、将此函数的地址注册给调用者; 
3、特定的事件或条件发生时,调用者使用函数指针调用回调函数。 
注:为什么要特定事件或条件发生?不应该随时都可以调用回调函数吗? 
以下是回调函数的两种使用方式(简单理解): 

1、

#include <stdio.h>
typedef int(*callback)(int,int);

int add(int a,int b,callback p){
    return (*p)(a,b);
}

int add(int a,int b){
    return a+b;
}
int main(int argc,char *args[]){
    int res = add(4,2,add);
    printf("%d\n",res);
    return 0;
}

在这个例子中,可以看到,我们定义了一个callbak的函数指针,参数为两个int,返回值为int,通过调用函数地址来进行简单的相加运算。 

2、

#include <stdio.h>
typedef int (callBack)(const void *buffer,size_t size,char *p_out);

void callFunc(callBack *consume_bytes, char *p_out) {
    printf("callFunc\n");
    const void *buffer = NULL;
    consume_bytes(buffer,0,p_out); //传入值可以随便填
}

int callBackFunc(const void *buffer, size_t size, char *p_out){
    printf("callBackFunc\n");
    memset(p_out,0x00,sizeof(char)*100);
    strcpy(p_out,"encoderCallback:this is string.");
    return 1;
}

int main(int argc,char *args[]){
    char p_out[100];
    callFunc(callBackFunc,p_out);
    printf("%s\n",p_out);
    return 0;
}

可以把回调函数和调用函数封装承类再调用。

二、实验代码分析

linktableInternal.h:定义了链表头结点 LinkTable和链表的结点LinkTableNode。

#include <pthread.h>

/*
 * LinkTable Node Type
 */
struct LinkTableNode
{
    struct LinkTableNode * pNext;
};
/*
 * LinkTable Type
 */
struct LinkTable
{
    struct LinkTableNode *pHead;
    struct LinkTableNode *pTail;
    int			SumOfNode;
    pthread_mutex_t mutex;

};

linktable.h:  声明了一些链表相关的操作函数,包括创建链表、添加链表结点、删除链表结点等。

#ifndef _LINK_TABLE_H_
#define _LINK_TABLE_H_

#include "linktableInternal.h"

#define SUCCESS 0
#define FAILURE (-1)

/*
 * LinkTable Node Type
 */
typedef struct LinkTableNode tLinkTableNode;

/*
 * LinkTable Type
 */
typedef struct LinkTable tLinkTable;

/*
 * Create a LinkTable
 */
tLinkTable * CreateLinkTable();
/*
 * Delete a LinkTable
 */
int DeleteLinkTable(tLinkTable *pLinkTable);
/*
 * Add a LinkTableNode to LinkTable
 */
int AddLinkTableNode(tLinkTable *pLinkTable, tLinkTableNode * pNode);
/*
 * Delete a LinkTableNode from LinkTable
 */
int DelLinkTableNode(tLinkTable *pLinkTable, tLinkTableNode * pNode);
/*
 * Search a LinkTableNode from LinkTable
 * int Conditon(tLinkTableNode * pNode, void * args);
 */
tLinkTableNode * SearchLinkTableNode(tLinkTable *pLinkTable, int Conditon(tLinkTableNode * pNode, void * args), void * args);
/*
 * get LinkTableHead
 */
tLinkTableNode * GetLinkTableHead(tLinkTable *pLinkTable);
/*
 * get next LinkTableNode
 */
tLinkTableNode * GetNextLinkTableNode(tLinkTable *pLinkTable, tLinkTableNode * pNode);

#endif /* _LINK_TABLE_H_ */

linktable.c :对linktable.h声明的操作的具体实现。

在menu.c中,则定义了与具体业务相关的数据结构DataNode和操作,编写了主程序运行逻辑。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "linktable.h"

int Help();
int Quit();

#define CMD_MAX_LEN 128
#define DESC_LEN    1024
#define CMD_NUM     10


/* data struct and its operations */

typedef struct DataNode
{
    tLinkTableNode head;
    char*   cmd;
    char*   desc;
    int     (*handler)();
} tDataNode;


int SearchCondition(tLinkTableNode * pLinkTableNode, void * args)
{
    char * cmd = (char*) args;
    tDataNode * pNode = (tDataNode *)pLinkTableNode;
    if(strcmp(pNode->cmd, cmd) == 0)
    {
        return  SUCCESS;  
    }
    return FAILURE;	       
}

/* find a cmd in the linklist and return the datanode pointer */
tDataNode* FindCmd(tLinkTable * head, char * cmd)
{
    return  (tDataNode*)SearchLinkTableNode(head, SearchCondition, (void*)cmd);
}

/* show all cmd in listlist */
int ShowAllCmd(tLinkTable * head)
{
    tDataNode * pNode = (tDataNode*)GetLinkTableHead(head);
    while(pNode != NULL)
    {
        printf("%s - %s\n", pNode->cmd, pNode->desc);
        pNode = (tDataNode*)GetNextLinkTableNode(head, (tLinkTableNode *)pNode);
    }
    return 0;
}

int InitMenuData(tLinkTable ** ppLinktable)
{
    *ppLinktable = CreateLinkTable();
    tDataNode* pNode = (tDataNode*)malloc(sizeof(tDataNode));
    pNode->cmd = "help";
    pNode->desc = "Menu List:";
    pNode->handler = Help;
    AddLinkTableNode(*ppLinktable, (tLinkTableNode *)pNode);
    pNode = (tDataNode*)malloc(sizeof(tDataNode));
    pNode->cmd = "version";
    pNode->desc = "Menu Program V1.0";
    pNode->handler = NULL; 
    AddLinkTableNode(*ppLinktable, (tLinkTableNode *)pNode);
    pNode = (tDataNode*)malloc(sizeof(tDataNode));
    pNode->cmd = "quit";
    pNode->desc = "Quit from Menu Program V1.0";
    pNode->handler = Quit; 
    AddLinkTableNode(*ppLinktable, (tLinkTableNode *)pNode);
 
    return 0; 
}

/* menu program */

tLinkTable * head = NULL;

int main()
{
    InitMenuData(&head); 
   /* cmd line begins */
    while(1)
    {
        char cmd[CMD_MAX_LEN];
        printf("Input a cmd number > ");
        scanf("%s", cmd);
        tDataNode *p = FindCmd(head, cmd);
        if( p == NULL)
        {
            printf("This is a wrong cmd!\n ");
            continue;
        }
        printf("%s - %s\n", p->cmd, p->desc); 
        if(p->handler != NULL) 
        { 
            p->handler();
        }
   
    }
}

int Help()
{
    ShowAllCmd(head);
    return 0; 
}

int Quit()
{
    exit(0);
}

代码中的回调函数使用示例之一如下:


/*
 * Search a LinkTableNode from LinkTable
 * int Condition(tLinkTableNode * pNode, void * args);
 */
tLinkTableNode * SearchLinkTableNode(tLinkTable *pLinkTable, 
                        int Condition(tLinkTableNode * pNode, void * args),
                        void * args)
{
    if(pLinkTable == NULL || Condition == NULL)
    {
        return NULL;
    }
    tLinkTableNode * pNode = pLinkTable->pHead;
    while(pNode != NULL)
    {    
        if(Condition(pNode, args) == SUCCESS)
        {
            return pNode;				    
        }
        pNode = pNode->pNext;
    }
    return NULL;

SearchLinkTableNode函数,其中有一个函数作为参数,这个作为参数的函数就是callback函数。在SearchLinkTableNode中会调用SearchCondition来检查是否满足要求。实际上SearchLinkTableNode函数并不在意SearchCondition函数是怎么实现的,它只需要SearchCondition函数有两个指定类型的输入参数和一个int型的返回值就可以了。

三、总结

使用回调(callback)函数的好处是可以解耦,在主入口程序中,把回调函数像参数一样传入库函数。这样一来,只要我们改变传进库函数的参数,就可以实现不同的功能,且不需要修改库函数的实现,变的很灵活。

 

学号:530

...全文
210 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

571

社区成员

发帖
与我相关
我的任务
社区描述
软件工程教学新范式,强化专项技能训练+基于项目的学习PBL。Git仓库:https://gitee.com/mengning997/se
软件工程 高校
社区管理员
  • 码农孟宁
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧