gpt4 book ai didi

linux-kernel - linux源码中带方法的struct结构

转载 作者:太空狗 更新时间:2023-10-29 15:31:12 25 4
gpt4 key购买 nike

我正在阅读 android 内核代码,我正面临这种数据结构,

static const struct file_operations tracing_fops = {
.open = tracing_open,
.read = seq_read,
.write = tracing_write_stub,
.llseek = tracing_seek,
.release = tracing_release,
};

有人可以大致解释一下这个语法吗?等式右侧是函数名称,&tracing_fops 稍后作为参数传递给另一个初始化 debugfs 文件系统的函数。

最佳答案

作业是使用复合文字的示例。根据C99 Section #6.5.2.5 :

A postfix expression that consists of a parenthesized type namefollowed by a brace- enclosed list of initializers is a compoundliteral. It provides an unnamed object whose value is given by theinitializer list.

在更简单的版本中,根据 GCC docs: Compound literals :

A compound literal looks like a cast of a brace-enclosed aggregateinitializer list. Its value is an object of the type specified in thecast, containing the elements specified in the initializer. Unlike theresult of a cast, a compound literal is an lvalue. ISO C99 and latersupport compound literals. As an extension, GCC supports compoundliterals also in C90 mode and in C++, although as explained below, theC++ semantics are somewhat different.

一个简单的例子:

struct foo { int x; int y; };

func() {
struct foo var = { .x = 2, .y = 3 };
...
}

在问题的示例中,struct file_operations 定义在 include/linux/fs.htracing_fopskernel/trace/trace.c 中Linux 源代码树中的文件。

struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
...
};

open, read, write 都是Function Pointers这是指向函数的指针。取消引用函数指针后,它可以用作正常的函数调用。 tracing_fops 结构是file_operations 类型。函数指针成员的值使用复合文字分配给同一 trace.c 文件中的函数。

使用复合文字,我们不必显式指定/分配结构类型中的所有成员,因为其他成员都设置为零或空。使用复合文字创建的结构对象可以传递给函数而不依赖于成员顺序。两侧的函数参数应该相同。例如

的参数
int (*open) (struct inode *, struct file *);

相同
int tracing_open(struct inode *inode, struct file *file);

在面向对象编程中,这个想法有点类似于Virtual Function Table .

关于linux-kernel - linux源码中带方法的struct结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56405875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com