C语言链表常用宏——offsetof和container_of

链表是内核最经典的数据结构之一,说到链表就不得不提及内核最经典(没有之一)的宏container_of

先看看代码:

#include <stddef.h>
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE*)0)->MEMBER)

#define container_of(ptr, type, member) ({          \
        const typeof( ((type *)0)->member ) *__mptr = (const typeof( ((type *)0)->member ) *)(ptr); \
        (type *)( (char *)__mptr - offsetof(type,member) );})

几个关键内容分析一下:

typeof

typeof是GNU对C新增的一个扩展关键字,用于获取一个对象的类型,在很多时候我们处理的对象通常是一个指针,而此时如果想知道指针所指向的对象的类型,typeof就派上用场了,详见GNU的官方文档:http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

offsetof

offsetof是返回结构体TYPEMEMBER成员相对于结构体首地址的偏移量,以字节为单位。

(TYPE *)0,将 0 强制转换为TYPE型指针,记 p = (TYPE *)0p是指向TYPE的指针,它的值是0。那么 p->MEMBER 就是 MEMBER 这个元素了,而&(p->MEMBER)就是MEMBER的地址,编译器认为0是一个有效的地址,则基地址为0,这样就巧妙的转化为了TYPE中的偏移量。再把结果强制转换为size_t型的就OK了。

container_of

container_of的主要作用是根据一个结构体变量中的一个域成员变量的指针来获取指向整个结构体变量的指针。

创建一个类型为const typeof( ((type *)0)->member ) *,即类型为type结构的member域所对应的对象类型的常指针__mptr,并用ptr初始化之,这样一来,__mptr就指向了某一个typemember域。因为数据结构是顺序存储的,此时如果知道membertype结构中的相对偏移,那么用__mptr减去此偏移便是ptr所属的type的地址。

container_of最典型的应用就是根据链表节点获取链表上的元素对象。

附上Linux内核的list.h

/*
 * list.h
 * list operations
 *
 * copied from Linux_Kernel_Dir/include/linux/list.h
 */

#ifndef _MG_LIST_H
  #define _MG_LIST_H

#include "mgconfig.h"
struct list_head {
    struct list_head *next, *prev;
};

typedef struct list_head list_t;

#define LIST_HEAD_INIT(name) { &(name), &(name) }

/* define and init a list head */
#define LIST_HEAD(name) \
    struct list_head name = LIST_HEAD_INIT(name)

/* init a list head */
#define INIT_LIST_HEAD(ptr) do { \
    (ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)

/*
 * Insert a new entry between two known consecutive entries. 
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static inline void __list_add(struct list_head * new,
    struct list_head * prev,
    struct list_head * next)
{
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

/**
 * list_add - add a new entry
 * @new: new entry to be added
 * @head: list head to add it after
 *
 * Insert a new entry after the specified head.
 * This is good for implementing stacks.
 */
static inline void list_add(struct list_head *new, struct list_head *head)
{
    __list_add(new, head, head->next);
}

/**
 * list_add_tail - add a new entry
 * @new: new entry to be added
 * @head: list head to add it before
 *
 * Insert a new entry before the specified head.
 * This is useful for implementing queues.
 */
static inline void list_add_tail(struct list_head *new, struct list_head *head)
{
    __list_add(new, head->prev, head);
}

/*
 * Delete a list entry by making the prev/next entries
 * point to each other.
 *
 * This is only for internal list manipulation where we know
 * the prev/next entries already!
 */
static inline void __list_del(struct list_head * prev,
                  struct list_head * next)
{
    next->prev = prev;
    prev->next = next;
}

/**
 * list_del - deletes entry from list.
 * @entry: the element to delete from the list.
 * Note: list_empty on entry does not return true after this, the entry is in an undefined state.
 */
static inline void list_del(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
}

/**
 * list_del_init - deletes entry from list and reinitialize it.
 * @entry: the element to delete from the list.
 */
static inline void list_del_init(struct list_head *entry)
{
    __list_del(entry->prev, entry->next);
    INIT_LIST_HEAD(entry); 
}

/**
 * list_empty - tests whether a list is empty
 * @head: the list to test.
 */
static inline int list_empty(struct list_head *head)
{
    return head->next == head;
}

/**
 * list_entry - get the struct for this entry
 * @ptr:    the &struct list_head pointer.
 * @type:    the type of the struct this is embedded in.
 * @member:    the name of the list_struct within the struct.
 */
#define list_entry(ptr, type, member) \
    ((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))

/**
 * list_for_each    -    iterate over a list
 * @pos:    the &struct list_head to use as a loop counter.
 * @head:    the head for your list.
 */
#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); pos = pos->next)
            
/**
 * list_for_each_safe    -    iterate over a list safe against removal of list entry
 * @pos:    the &struct list_head to use as a loop counter.
 * @n:        another &struct list_head to use as temporary storage
 * @head:    the head for your list.
 */
#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
        pos = n, n = pos->next)

/**
 * list_for_each_ex    -    iterate over a list
 * @pos:    the &struct list_head to use as a loop counter.
 * @head:   the head for your list.
 * @begin:  the previous item of the begining item
 */
#define list_for_each_ex(pos, head, begin) \
    for (pos = (begin)->next; pos != (head); pos = (pos)->next)

/**
 * list_for_index    -    iterate over a list for index
 * @pos:    the &struct list_head to use as a loop counter.
 * @head:    the head for your list.
 */
#define list_for_index(pos, i, head, index) \
    for (pos = (head)->next, i=0; (pos != (head) && i < index); pos = pos->next,i++)


static inline int list_add_by_index(struct list_head *new, struct list_head *head, int index)
{
    list_t *pos = head;
    int i = -1;

    if (index >= 0) {
        for (pos = (head)->next, i=0; (pos != (head) && i < index); pos = pos->next,i++);
    }
    list_add_tail (new, pos);
    return i;
}


/* added for normal list operations */
#define GETBY_EX(func, head, entrytype, member, datatype, ret, equal_cond) \
        void* func (datatype data) \
        { \
            list_t *me; \
            entrytype *pdata; \
            int i = 0; \
            \
            list_for_each(me, head) { \
                pdata = list_entry(me, entrytype, member); \
                if (equal_cond) \
                    return ret; \
            } \
            return NULL; \
        }

#define GET_LIST_BY_DATA(func, head, entrytype, member, datamember, datatype) \
        GETBY_EX(func, head, entrytype, member, datatype, me, (pdata->datamember == data))

#define GET_ENTRY_BY_DATA(func, head, entrytype, member, datamember, datatype) \
        GETBY_EX(func, head, entrytype, member, datatype, pdata, (pdata->datamember == data))

/* for string */
#define GET_LIST_BY_STRING(func, head, entrytype, member, datamember, datatype) \
        GETBY_EX(func, head, entrytype, member, datatype, me, (strcmp(pdata->datamember,data)==0))

#define GET_ENTRY_BY_STRING(func, head, entrytype, member, datamember, datatype) \
        GETBY_EX(func, head, entrytype, member, datatype, pdata, (strcmp(pdata->datamember,data)==0))

/* for more compicated */
#if 0
#define GET_ENTRY_BY_STRUCT(func, head, entrytype, member, datamember, datatype, equal_cond) \
        GETBY_EX(func, head, entrytype, member, datatype, pdata, equal_cond)
#endif

/* for index */
#define GET_ENTRY_BY_INDEX(func, entrytype, member) \
        static inline entrytype* func (list_t *head, int index) \
        { \
            list_t *me; \
            int i = 0; \
            \
            list_for_each(me, head) { \
                if (i++ == index) \
                    return list_entry(me, entrytype, member); \
            } \
            return NULL; \
        }

#define GET_ENTRY_INDEX(func, entrytype, member) \
        static inline int func (list_t *head, entrytype* entry) \
        { \
            list_t *me; \
            int i = 0; \
            \
            list_for_each(me, head) { \
                if (entry == list_entry(me, entrytype, member)) \
                    return i; \
                i++; \
            } \
            return -1; \
        }


#endif /* _MG_LIST_H */

例子

struct entry {
  int data;
  list_link llnk; //挂载点可以在任意位置,container_of能找到结构体地址
}
list_link *lhead;
struct entyr *pe;
list_for_each(pos, lhead) { //顺着挂载点遍历
  pe = container_of(pos, struct entry, llnk); //取出结构体
  //to do something with pe
}

我是咕咕鸡,一个还在不停学习的全栈工程师。
热爱生活,喜欢跑步,家庭是我不断向前进步的动力。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容