(*fun_hangld[buf[0]])(); 通过指针数组函数来调用放在数组里面的函数

定义数组函数集合:

void (*fun_hangld[])()={    //函数的存放集合
    Fun1,
    Fun2,
    Fun3,
    Fun4
};
 

通过while(1){(*fun_hangld[buf[0]])();}一直读取buf[0]的值,来确定是进行那个函数。这种思想在进行模块化时很好用,比如按键来控制屏幕之间的对应关系,一个按键值,代表不同界面的显示内容,把要显示的每一页面内容分为一个个函数来对应,buf[]的值就代表按键要选择的页面,可以实现高效简洁循环显示。

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
#include <string.h>
#include <errno.h>

pthread_t pthread;
pthread_t pthread1;


typedef struct pipe{
	int list;
	int pipes[2];
}pipeobj,*Ppipe;

Ppipe pipe_create();
void fun(void);
Ppipe PIPE;
int LIST;
void Fun1(void);
void Fun2(void);
void Fun3(void);
void Fun4(void);

void (*fun_hangld[])()={	//函数的存放集合
	Fun1,
	Fun2,
	Fun3,
	Fun4
};

void Fun1(void){
	printf("in Fun1 \n");
	return;	
}

void Fun2(void){
	printf("in Fun2 \n");
	return;	
}

void Fun3(void){	
	printf("in Fun3 \n");
	return;	
}

void Fun4(void){
	printf("in Fun4 \n");
	return;	
}


Ppipe pipe_create()
{
	Ppipe h_pipe;
	h_pipe=calloc(1,sizeof(pipeobj));
	if(NULL==h_pipe){
		perror("h_pipe");
		return NULL;
	}
	if(pipe(h_pipe->pipes)<0){
		free(h_pipe);
		return NULL;
	}
	return h_pipe;
}

void fun_write(void)
{
	int buf[10];
	
	if(NULL==PIPE){
		perror("PIPE");
		exit(-1);
	}

	while(1)
	{
		bzero(buf,sizeof(buf));
		//fgets(buf,sizeof(buf),stdin);
		scanf("%d",&buf[0]);			//通过buf[0]的值来调用想要调用的函数
		write(PIPE->pipes[1],buf,sizeof(buf));		
	}
	return;
}

void fun_read(void)
{
	int buf[10];
	while(1)
	{
		int count=0;
		bzero(buf,sizeof(buf));
		count=read(PIPE->pipes[0],buf,sizeof(buf));
		if(count<0)
		{
			continue;
		}	
		printf("read buf的内容是:%d\n",buf[0]);
		
		(*fun_hangld[buf[0]])();	//不断读取buf[0]的值,来决定调用哪个函数
	}
	printf("6\n");
	return;
}

int main(void)
{
	PIPE=pipe_create();
	pthread_create(&pthread,NULL,(void *)&fun_write,NULL);
	pthread_create(&pthread1,NULL,(void *)&fun_read,NULL);
	printf("after main\n");
	while(1){
		sleep(1);
	}
	return 0;
}

编译执行结果:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值