In_of macro definition, contain_of macro

Source: Internet
Author: User

In_of macro definition, contain_of macro

Container_of is a common macro in Linux kernel. It is used to obtain the pointer of the structure from the pointer contained in a structure, generally, the first address of a member in the struct variable is obtained to obtain the first address of the entire struct variable.

 

Implementation Method:

Container_of (ptr, type, member );

 

In fact, its syntax is very simple, but some pointers are used flexibly. It consists of two steps:

Step 1: first define a temporary data type (obtained through typeof (type *) 0)-> member) with the same pointer Variable _ mptr as ptr, use it to save the ptr value.

Step 2: Use (char *) _ mptr to subtract the offset of member in the struct. The obtained value is the first address of the entire struct variable (the return value of the entire macro is the first address ).

The difficulty in the syntax is how to get the offset of the member to the struct?

 

For example, in Listing 1:

 1 #include <stdio.h> 2 #define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) 3 #define  container_of(ptr, type, member) ({                      \ 4                       const typeof( ((type *)0)->member ) *__mptr = (ptr);    \ 5                        (type *)( (char *)__mptr - offsetof(type,member) );}) 6 struct test_struct { 7            int num; 8           char ch; 9           float f1;10   };11  int main(void)12   {13           struct test_struct *test_struct;14           struct test_struct init_struct ={12,'a',12.3};15           char *ptr_ch = &init_struct.ch;16           test_struct = container_of(ptr_ch,struct test_struct,ch);17           printf("test_struct->num =%d\n",test_struct->num);18           printf("test_struct->ch =%c\n",test_struct->ch);19           printf("test_struct->ch =%f\n",test_struct->f1);20           return 0;21   }

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.