Linux内核链表管理的一些常用宏

来源:互联网 发布:unity3d安卓真机调试 编辑:程序博客网 时间:2024/06/08 19:23

对一些链表内核宏的记录备忘,小试用程序如下:

#include "stdafx.h"#include "iostream"#include <vector>#include <list>#include <typeinfo.h>#include <stdio.h>#include <stddef.h>#include <stdlib.h>using namespace std;#define offsetof(type, member) (size_t)&(((type *)0)->member)//linux//#define container_of(ptr, type, member) ({                      \//        const typeof(((type *) 0)->member) *__mptr = (ptr);     \//        (type *) ((char *) __mptr - offsetof(type, member));})//windows#define container_of(ptr, type, member)  \((type*)((char*)ptr - offsetof(type, member)))#define list_entry(ptr, type, member) \         container_of(ptr, type, member)struct AAA{int   i;int   j;double  d;AAA() { i = 0; j = 0; d = 0.0; };};struct test{int i;int j;char k;test() { i = 0; j = 0; k = 0; };};struct list_head {struct list_head *next, *prev;};struct example {int a;struct list_head list;int b;};int main(){struct AAA *pAAA;pAAA = new AAA();cout << "============ AAA ============" << endl;cout << "offsetof = " << offsetof(AAA, j) << endl;cout << "============ test ============" << endl;test temp;cout << "&temp = " << &temp << endl;cout << "&temp.j = " << &temp.j << endl;cout << "((size_t)&((test*)0)->j) = " << ((size_t)&((test*)0)->j) << endl;cout << "offsetof(test, j) = " << offsetof(test, j) << endl;cout << "============ example ============" << endl;example *ex = new example();cout << "offsetof(example, list) = " <<offsetof(example, list) << endl;cout << "list_entry(&ex->list, example, list) = "<< list_entry(&ex->list, example, list) << endl;(*(example*)container_of(&ex->list, example, list)).a = 1;(*(example*)container_of(&ex->list, example, list)).b = 3;cout << "ex->a = " << ex->a << endl;cout << "ex->b = " << ex->b << endl;    return 0;}

自己记录一下,可能以后经常会用到。

原创粉丝点击