C语言callback功能及命令列表实现代码

141 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

从网络上搜对应的代码不是很好找,参考了git的source code,修改了个建议的实现;方便后面在写命令的app时不重复造轮子;开源供大家参考;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
#define BARF_UNLESS_AN_ARRAY(arr) 0
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]) + BARF_UNLESS_AN_ARRAY(x))
 
/*
  struct of cmd list
*/
struct cmd_struct {
	const char *cmd;
	int (*fn)(int, const char **);
};
 
/*
  call back function
*/
int cmd_add(int argc, const char **argv)
{
	printf("add, %s", argv[1]);
	return 1; 
}
 
 
/*
  call back function
*/
int cmd_test(int argc, const char **argv)
{
	printf("test, %s", argv[1]);
	return 1; 
}
 
/*
  add commands list below for function call
*/
static struct cmd_struct commands[] = {
	{ "add", cmd_add },
	{ "test", cmd_test },
};
 
 
/*
  find the cmd from this function
*/
static struct cmd_struct *get_builtin(const char *s)
{
	int i;
	for (i = 0; i < ARRAY_SIZE(commands); i++) {
		struct cmd_struct *p = commands + i;
		if (!strcmp(s, p->cmd))
			return p;
	}
	return NULL;
}
 
/*
  call function cmd list
*/
static int run_builtin(struct cmd_struct *p, int argc, const char **argv)
{
	int status = 0;
	status = p->fn(argc, argv);
	return status;
}
 
 
/*
  main function
*/
int main(int argc, const char *argv[]) 
{
	struct cmd_struct *builtin;
	
	builtin = get_builtin(argv[1]);
	if (builtin)
		exit(!run_builtin(builtin, argc, argv));
	
	return 1;
}