为什么 container_of 宏会阻止内核的其他部分修改您的结构的唯一字段?

Why container_of macro prevents other parts of the kernel from modifying the unique fields of your structure?

我在网上找了资料,看完之后终于知道这个宏是如何工作的,它有什么作用,总的来说http://www.kroah.com/log/linux/container_of.html 最后,它说它防止内核的其他部分修改用于控制子系统代码的结构的唯一字段。 你能解释一下为什么吗?

抱歉我的英语不好。

您链接到的 webpage 有以下示例:

struct i2c_driver {
        char name[32];
        struct device_driver driver;
};

Linux 设备驱动核心只会关心 struct device_driver 而不会关心与 struct i2c_driver 相关的细节。这是设备驱动程序核心关心的抽象级别。因此,在 Linux 设备驱动程序核心中,将传递指向 struct device_driver 的指针,而不是指向设备特定结构的指针。如果你有一个 struct device_driver,你不能在没有其他知识的情况下确定什么类型的结构包含 struct device_driver

使用面向 object 的编程术语打个比方:struct i2c_driverstruct device_driver 的 child "class"。在面向 object 的编程中,如果没有一些其他信息,您不能从 parent 类型(例如 struct device_driver)转到 child 类型(例如 struct i2c_driver),例如作为使用 typeof 操作或类似操作获得的信息。 类似地,如果某段代码有一个指向 struct device_driver 的指针,除非它对指针指向的内容做出一些假设,否则它不会尝试访问任何 struct i2c_driver 字段。

请注意,"prevent" 确实不是我会选择的词,因为至少在我看来 "prevent" 暗示有一些 compile-time 或 run-time 保护将阻止这种情况发生。不是这种情况。相反,写得很好 遵守关于设备驱动程序抽象的约定的代码将不会操纵 "child" object 字段。然而,除了打破抽象之外,没有什么可以阻止某人这样做。

最后,你所指的那句话之前的句子对此有所说明:

The driver core only passes in the type of driver structure registered with it, so this type of manipulation is safe. This also prevents other parts of the kernel from modifying the unique fields of the structure used to control the subsystem's code.

基本上,重申驱动核心只关心struct device_driver而不关心任何特定于设备的东西。