通过结构成员获得结构地址的例子

本文介绍了一个基于Linux环境的回调函数示例,展示了如何利用结构成员获取成员所在结构的地址,并遍历链表来查找匹配项并调用相应的回调函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//通过结构成员获得成员所在结构的地址的例子
#define list_entry(ptr, type, member) \
	container_of(ptr, type, member)

#define list_for_each(pos, head) \
	for (pos = (head)->next; pos != (head); \
        	pos = pos->next)

struct list_head {
	struct list_head *next, *prev;
};

typedef struct HiBUS_srv_struct{
	char ID[32];/*HiBUS_ID*/
	char addr[32];/*HiBUS_ADDR*/
	void *user;/*user application pointer*/
	HiBUS_cb_f cb;/*event callback function*/
	
	/*the following is srv internal members*/
	struct list_head srv_list;/*link into srv_list_head*/
	int is_cbed;/*is any async event incoming and cb is called*/
	int event_ID;/*event ID*/
	
	int shoud_free;
}HiBUS_srv_t;

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


static int HiBUS_srv_callback(const char *ID, int event_ID,const char *para)
{
	struct list_head *entry;
	HiBUS_srv_t *srv_p;

	//pthread_mutex_lock(&HiBUS_srv_locker);
	hxSDK_mutex_lock(&HiBUS_srv_locker);//edit by hanln
	list_for_each(entry,&HiBUS_srv_list_head)
	{
		srv_p = list_entry(entry,HiBUS_srv_t, srv_list);

		if(!strcmp(srv_p->ID,ID))
		{
			DBG("HiBUS_srv ID %s is callback......",ID);
			srv_p->cb(event_ID,srv_p->user,(void*)para);

			srv_p->event_ID = event_ID;
			srv_p->is_cbed = 1;
			break;//add by phj 2009.2.11
		}
	}
	//pthread_mutex_unlock(&HiBUS_srv_locker);
	hxSDK_mutex_unlock(&HiBUS_srv_locker);//edit by hanln

	return 0;
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值