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

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

#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;
}


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值