参考:https://www.cnblogs.com/chenyuming507950417/archive/2012/01/02/2310114.html
#include <stdio.h>
typedef void (*P)(void);
void fun1(void)
{
printf("hello world\n");
}
void fun2(void)
{
printf("cbs\n");
}
int main(void)
{
P p;
p = fun1;
p();
p = fun2;
p();
return 0;
}
#include <stdio.h>
typedef void (*P)(void);
void printf_text(void)
{
printf("hello world\n");
}
void call_printf_text(P p)
{
p();
}
int main(void)
{
P p = printf_text;
call_printf_text(p);
return 0;
}
#include <stdio.h>
typedef void (*P)(const char *);
void printf_text(const char *str)
{
printf("%s\n",str);
}
void call_printf_text(P p,const char *str)
{
p(str);
}
int main(void)
{
P p = printf_text;
call_printf_text(p,"hello cbs");
return 0;
}
#include <stdio.h>
#include <string.h>
/************上级的代码*************/
typedef void (*P1)(const char *);
typedef void (*P2)(const char *,int);
typedef struct
{
P1 p1;
P2 p2;
}Fun;
void call(Fun *funs)
{
const char *str1 = "shun";
const char *str2 = "com";
int len = strlen(str2);
funs->p1(str1);//运行时call
funs->p2(str2,len);//运行时call
}
/***********************************/
/************程序员根据上级的typedef定义并实现自己的方法****************/
void fun1(const char *str)
{
printf("%s\n",str);
}
void fun2(const char *str,int len)
{
printf("%s\n",str);
printf("%d\n",len);
}
Fun funs = {fun1,fun2};
/******************最后根据上级的结构体打包函数指针*********************/
int main(void)
{
call(&funs);
return 0;
}