在学习编写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;
}
函数指针作为结构体成员的另一个例子