1、结构体的初始化
static struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
以前学习C语言的时候没有见过struct的这种初始化方式。这其实是C语言的新标准。Struct一共有三种初始化的方式:
int main(void){
struct sct{
int age;
char *name;
};
// way 1
struct sct s1={1,"aa"};
// way 2
struct sct s2={
.age=1,
.name="bb"
};
//way 3
struct sct s3={
age:1,
name:"cc"
};
printf("%d,%s\n",s1.age,s1.name);
printf("%d,%s\n",s3.age,s3.name);
printf("%d,%s\n",s2.age,s2.name);
return 0;
}
2、函数指针
static struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
file_operations 结构体初始化传入的4个变量是函数名,而不是普通的变量。这就涉及到指向函数的指针相关知识点。指针本身也是一个变量,作为变量本身,其会占用内存空间,其内存空间同样可以存储数据,并且可以读取该数据。而作为引用使用时,即*p时,首先是需要读取其地址存储的数据,将其视为一个地址,再从这个地址中读取数据,作为结果。(http://blog.chinaunix.net/uid-23629988-id-3084750.html)
简单模拟函数指针的用法:
#include
struct file_operations{
void (*open)();
void (*close)();
};
void file_open(){
printf("file is open\n");
}
void file_close(){
printf("file is close\n");
}
void register_dev(struct file_operations *fops){
fops->open();
fops->close();
}
int main(void){
struct file_operations fops={
.open=file_open,
.close=file_close
};
register_dev(&fops);
return 0;
}