libevent里list的用法

//list.h

#include<stdio.h>

#ifndef TAILQ_HEAD
#define TAILQ_HEAD(name, type)\
struct name\
{\
struct type* tqh_first;\
struct type** tqh_last;\
}
#endif

#ifndef TAILQ_ENTRY
#define TAILQ_ENTRY(type)\
struct\
{\
struct type* tqe_next;\
struct type** tqe_prev;\
}
#endif

#define TAILQ_INIT(head) do { \
(head)->tqh_first = NULL; \
(head)->tqh_last = &(head)->tqh_first; \
} while (0)

#define TAILQ_INSERT_TAIL(head, elm, field) do { \
(elm)->field.tqe_next = NULL; \
(elm)->field.tqe_prev = (head)->tqh_last; \
*(head)->tqh_last = (elm); \
(head)->tqh_last = &(elm)->field.tqe_next; \
} while (0)


/*
必须写到Node的开头才能转换后是最后一个元素 TAILQ_ENTRY(Node) next;
*/
//libevent里的 原理就是tqh_last指向最后一个元素的tqe_next,而tqe_next又是Node结构体的第一个成员变量,强制转换后就是整个的Node对象
//#define TAILQ_LAST(head, headname) \
// (*(((struct headname *)((head)->tqh_last))->tqh_last))

//(head)的括号不能少  (size_t)不能少, head里必须有元素时才能用下面的
//自己写的只是为了测试由成员找到该成员所属的对象
#define TAILQ_LAST(head, nodename, field)\

((struct nodename*)(((size_t)((head)->tqh_last))-(size_t)&((((struct nodename*)(0))->field).tqe_next)))

//list.cpp

#include<iostream>
using namespace std;
#include"list.h"

struct Node
{
int l;
TAILQ_ENTRY(Node) next;
int i;
};

TAILQ_HEAD(listhead, Node);

int main()
{
struct listhead mylisthead;
TAILQ_INIT(&mylisthead);

Node *node = new Node;
node->i = 11;
printf("node 1:%d\n", node);
//TAILQ_INSERT_TAIL(&mylisthead, node, next);
printf("last: %d\n", mylisthead.tqh_last);
Node *node2 = new Node;
printf("node 2:%d\n", node2);
printf("node 2:%d\n", &node2->next.tqe_next);
node2->i = 21;
//TAILQ_INSERT_TAIL(&mylisthead, node2, next);

for(node = mylisthead.tqh_first; node != NULL; node = node->next.tqe_next)
{
printf("node - > i : %d \n", node->i);
}
printf("last: %d\n", mylisthead.tqh_last);
if((mylisthead.tqh_last) != NULL)
{
Node *p = (Node*)(((size_t)((&mylisthead)->tqh_last)) - (size_t)&((((struct Node*)(0))->next).tqe_next));
printf("last %d\n", p->i);
printf("last\n");
}

Node *p = TAILQ_LAST(&mylisthead, Node, next);
printf("p : %d\n", p->i);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值