C语言 函数指针 作为结构体成员 | Linux LED程序框架

在学习编写led驱动程序框架中有一段程序难以理解

4-7行

struct led_operations {
	int (*init) (int which); 			 /* 初始化LED, which-哪个LED */       
	int (*ctl) (int which, char status); /* 控制LED, which-哪个LED, status:1-亮,0-灭 */
};

函数指针 作为结构体成员,其中有两个函数指针,

分别为,返回值为int的函数指针*init,它的参数为int类型的which

               返回值为int的函数指针*ctl,它的参数为int类型的which,char类型的status

第9行

struct led_operations *get_board_led_opr(void);

从get_board_led_opr(void)这个函数指针指向的地址中获取结构体成员的参数。

面向对象的程序设计

1. 定义LED操作结构体

#ifndef _LED_OPR_H
#define _LED_OPR_H

struct led_operations {
	int (*init) (int which); /* 初始化LED, which-哪个LED */       
	int (*ctl) (int which, char status); /* 控制LED, which-哪个LED, status:1-亮,0-灭 */
};

struct led_operations *get_board_led_opr(void);


#endif

2.针对不同单板具体实现LED操作

static int board_demo_led_init (int which) /* 初始化LED, which-哪个LED */	   
{
	
	printk("%s %s line %d, led %d\n", __FILE__, __FUNCTION__, __LINE__, which);
	return 0;
}

static int board_demo_led_ctl (int which, char status) /* 控制LED, which-哪个LED, status:1-亮,0-灭 */
{
	printk("%s %s line %d, led %d, %s\n", __FILE__, __FUNCTION__, __LINE__, which, status ? "on" : "off");
	return 0;
}

static struct led_operations board_demo_led_opr = {
	.init = board_demo_led_init,
	.ctl  = board_demo_led_ctl,
};

struct led_operations *get_board_led_opr(void)
{
	return &board_demo_led_opr;
}

 3. 驱动程序调用LED操作函数

部分代码

struct led_operations *p_led_opr;  //定义一个指向led_operations的结构体指针

/* 从板子上获得GPIO具体的信息 */
p_led_opr = get_board_led_opr();   //结构体指针p_led_opr指向board_demo.c中的设定的LEDinit ctl



static int led_drv_open (struct inode *node, struct file *file)
{	 
	int minor = iminor(inode);	//得到次设备号
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	/* 根据次设备号初始化IO */
	p_led_opr->init(minor);

	return 0;
}


static ssize_t led_drv_write (struct file *file, const char __user *buf, size_t size, loff_t *offset)
{
	/*从应用程序得到数据,1/0 */
	int err;
	char status;
	struct inode *inode = file_inode(file);
	int minor = iminor(inode);				//从文件中得到次设备号
	printk("%s %s line %d\n", __FILE__, __FUNCTION__, __LINE__);
	
	/*用户空间传入的buf,把里面的数据传给status,传1字节的数据*/
	err = copy_from_user(&c, buf, 1);

	/*根据次设备号和status控制LED高低电平*/
	p_led_opr->ctl(minor, status);
	
	return 0;
}
函数指针作为结构体成员的另一个例子

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值