From: Ian Campbell Subject: Re: [PATCH 09/11] libxl: New convenience macro CONTAINER_OF Date: Fri, 27 Jan 2012 15:22:55 +0000 Message-ID: <1327677775.26983.184.camel@zakaz.uk.xensource.com> References: <1327598457-28261-1-git-send-email-ian.jackson@eu.citrix.com> <1327598457-28261-10-git-send-email-ian.jackson@eu.citrix.com> Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Return-path: In-Reply-To: <1327598457-28261-10-git-send-email-ian.jackson@eu.citrix.com> List-Unsubscribe: , List-Post: List-Help: List-Subscribe: , Sender: xen-devel-bounces@lists.xensource.com Errors-To: xen-devel-bounces@lists.xensource.com To: Ian Jackson Cc: "xen-devel@lists.xensource.com" List-Id: xen-devel@lists.xenproject.org On Thu, 2012-01-26 at 17:20 +0000, Ian Jackson wrote: > Provide a convenient and type-safe wrapper which does the correct > dance to subtract offsetof. This is very similar to the > "container_of" macro in the Linux kernel, but it has an additional > feature that instead of the type argument you may also pass an > expression of that type; this makes initialising a variable with > CONTAINER_OF easier. > > Signed-off-by: Ian Jackson Acked. > --- > tools/libxl/libxl_internal.h | 29 +++++++++++++++++++++++++++++ > 1 files changed, 29 insertions(+), 0 deletions(-) > > diff --git a/tools/libxl/libxl_internal.h b/tools/libxl/libxl_internal.h > index 044eeb4..095dbce 100644 > --- a/tools/libxl/libxl_internal.h > +++ b/tools/libxl/libxl_internal.h > @@ -1235,6 +1235,35 @@ _hidden void libxl__ao__destroy(libxl_ctx*, libxl__ao *ao); > * Convenience macros. > */ > > +/* > + * CONTAINER_OF work like this. Given: > + * typedef struct { > + * ... > + * member_type member_name; > + * ... > + * } outer_type; > + * outer_type outer, *outer_var; > + * member_type *inner_ptr = &outer->member_name; > + * > + * Then, effectively: > + * outer_type *CONTAINER_OF(member_type *inner_ptr, > + * *outer_var, // or type name for outer_type > + * member_name); > + * > + * So that: > + * CONTAINER_OF(inner_ptr, *outer_var, member_name) == &outer > + * CONTAINER_OF(inner_ptr, outer_type, member_name) == &outer > + */ > +#define CONTAINER_OF(inner_ptr, outer, member_name) \ > + ({ \ > + typeof(outer) *container_of_; \ > + container_of_ = (void*)((char*)(inner_ptr) - \ > + offsetof(typeof(outer), member_name)); \ > + (void)(&container_of_->member_name == \ > + (typeof(inner_ptr))0) /* type check */; \ > + container_of_; \ > + }) > + > > /* > * All of these assume (or define)