C 语言实现回调函数

优点
不需要改变调用的主函数,只需添加命令和相应函数。

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

static void cmd_hello(void)
{
     hello();
}

static void cmd_hi(void)
{
     hi();
}

static void cmd_exit(void)
{
    printf("process will exit!!!\n");
    exit(0);
}

void hello(void)
{
    printf("console output:hello\n");
}

void hi(void)
{
    printf("console output:hi\n");
}

typedef void (*callback) (void);
// define command struct
typedef struct cmd
{
    char name[10];      // define command name 
    callback func;      // define callback function
}cmd_t;

// define command array
const cmd_t cmd_tbl[] =
{
    {"hello",cmd_hello},
    {"hi",cmd_hi},
    {"exit",cmd_exit},
};
 
 
// find the callback function by command name
cmd_t* my_find(const char*val)
{
    int i;
    for(i=0;i<sizeof(cmd_tbl)/sizeof(cmd_tbl[0]);i++)
    {
        if(!strcmp(val,cmd_tbl[i].name))
        {
            return &cmd_tbl[i];
        }
    }
    return 0;
}

int main()
{
    char val[20] = {};
    cmd_t *cmd_ptr;
    while(1)
    {
        gets(val);
        cmd_ptr = my_find(val);
        if(cmd_ptr)
            cmd_ptr->func();
        else
            printf("no command\n");
    }

    return 0;
}
posted @ 2019-08-29 10:49  youngliu91  阅读(776)  评论(0编辑  收藏  举报