partial struct usage

B

Ben Pfaff

Phil Carmody said:
I had presumed Linux's definition:

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

was lifted from an early gcc definition, as a lot of things like that were.

It seems that someone else has questioned the seemingly necessary
additional line:
http://psomas.wordpress.com/2009/07/01/weird-kernel-macros-container_of/
"""
EDIT: Apparently, the first line is there for `type checking'. It
ensures that type has a member called member(howerver this is done by
offsetof macro too, I think), and if ptr isn't a pointer to the
correct type(the type of the member), the compiler will print a
warning, which can be useful for debuging.
"""

Which implies that it wasn't a gcc-ism after all.

({ }) and "typeof" are of course non-portable, but one can write
a more portable variant without them, as I have in GNU PSPP:

/* Given expressions A and B, both of which have pointer type,
expands to a void expression that causes a compiler warning if
A and B are not pointers to qualified or unqualified versions
of compatible types.

Examples similar to those given for CHECK_POINTER_HAS_TYPE,
above, can easily be devised. */
#define CHECK_POINTER_COMPATIBILITY(A, B) ((void) sizeof ((A) == (B)))

/* Given POINTER, a pointer to the given MEMBER within structure
STRUCT, returns the address of the STRUCT. */
#define UP_CAST(POINTER, STRUCT, MEMBER) \
(CHECK_POINTER_COMPATIBILITY (&((STRUCT *) 0)->MEMBER, POINTER), \
(STRUCT *) ((char *) (POINTER) - offsetof (STRUCT, MEMBER)))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top