简体   繁体   English

将指针包装在C中的结构中的目的

[英]The purpose of wrapping a pointer in struct in C

In Linux kernel code (up to 3.1.* ) I saw such structure definition: 在Linux内核代码(最多3.1。* )中,我看到了这样的结构定义:

struct skb_frag_struct {
    struct page *page;
    /* ... */

In newer kernel versions this has evolved into: 在较新的内核版本中,这已演变为:

struct skb_frag_struct {
    struct {
        struct page *p;
    } page;
    /* ... */

For what purpose could this wrapping be done in this particular case? 在这种特殊情况下,这种包装可以用于什么目的? And why it may be needed in general case? 为什么在一般情况下可能需要它?

It can be helpful in understanding a code change to use the Git Blame View: 理解代码更改以使用Git Blame视图会有所帮助:

https://github.com/torvalds/linux/blame/a978a5b8d83f795e107a2ff759b28643739be70e/include/linux/skbuff.h https://github.com/torvalds/linux/blame/a978a5b8d83f795e107a2ff759b28643739be70e/include/linux/skbuff.h

You can see what it says in the description of the commit where the change was made : 您可以在提交更改提交说明中看到它的内容:

net: add opaque struct around skb frag page net:在skb frag页面周围添加opaque结构

I've split this bit out of the skb frag destructor patch since it helps enforce the use of the fragment API. 我已将此位从skb frag析构函数补丁中分离出来,因为它有助于强制使用片段API。

So it seems this was done just to catch dangling references in the code which were making raw access to a pointer, and force usage of a higher level API. 因此,似乎只是为了捕获代码中的悬空引用,这些引用正在对指针进行原始访问,并强制使用更高级别的API。 It shouldn't add any runtime cost. 它不应该添加任何运行时成本。

As an aside: the last time I did this myself I had a kind of silly idea which is to split the name of the struct out to something like struct { struct page *ge; } pa; 顺便说一句:上次我自己这样做时,我有一种愚蠢的想法,即将结构名称拆分为struct { struct page *ge; } pa; struct { struct page *ge; } pa; ...this way the privileged code can read as fragstruct.pa.ge instead of fragstruct.page.p . ...这样,特权代码可以读取为fragstruct.pa.ge而不是fragstruct.page.p But outside of that being silly, an advantage of using the same name for the outer struct is helping guide old usages with clear errors. 但除此之外是愚蠢的,使用相同名称的外部结构的一个优点是帮助指导旧的用法有明显的错误。 Though as your confusion points out, a comment // don't access directly, use fragment API on the p member would probably have been appropriate in this case. 虽然你的困惑指出,评论// don't access directly, use fragment API在这种情况下,在p成员上// don't access directly, use fragment API可能是合适的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM