在Linux2.6版本的内核中,我们经常可以看到下面的结构体的定义和初始化。这在以前的C语言书中是极少见到的。下面的一个结构体来自到Linux内核中的一部分。在这个结构体中我们可以看到有普通的整型变量,也有函数的指针。
struct net_proto_family { int family; int (*create)(struct net *net, struct socket *sock, int protocol, int kern); struct module *owner; }; |
而在内核中可以使用下面的方法进行初始化。static const struct net_proto_family netlink_family_ops = { .family = PF_NETLINK, .create = netlink_create, .owner = THIS_MODULE, /* for consistency 8) */ }; |
下面是使用上面的结构体的一个小程序,其中还有结构体中的另外一种应用:
#include <stdio.h> #define PF_ID 10
enum { ID1 = 10, ID2, ID3, };
char *message = "message"; int create(int fd,char *name) { if(fd == 10) { printf ("I am create fd = %d,name = %s
",fd,name); } return 1; }
int output (int fd,char *name) { printf("I am output fd =%d,name = %s
",fd,name); return 1; }
int output_2 (int fd,char *name) { printf("I am output_2 fd = %d,name = %s
",fd,name); }
struct test_1 { int (*output)(int fd,char *name); };
struct test { int id; char name[50]; int (*print)(int fd,char *name); };
static struct test des ={
.id= PF_ID, .name ="frank", .print = create, };
struct test_1 table[] = { [ID1] = {.output = output}, [ID2] = {.output = output_2}, };
int main() { printf("des.PF_ID=%d
",des.id); printf("des.message= %s
",des.name); des.print(PF_ID,message); table[ID2].output(PF_ID,"table ID2"); table[ID1].output(PF_ID,"table ID1"); }
|
这里有一篇分析Linux内核这种数据结构比较详细的文章。
http://www.linuxidc.com/Linux/2011-07/39084htm