Container_of( ), a macro

EmbLogic RCD Labs
1 min readMar 28, 2020

Defined in <linux/kernel.h> , it takes three arguments, pointer, type, field.

Pointer : a pointer to device representation kernel data structure (c_dev) through a file system inode.

Type : data type of the device description user defined data structure as designed in device driver.

Field : device representation kernel data structure identifier as given in user defined device representation data structure (Dev)

It returns a pointer of type user defined device representation data structure (Dev), that can refer to locations in kernel space, IO space, device memory space. It act as interpret address from all these regions.

……………………………………………………………………………

#define container_of( ptr , type , field ) ({ \

const typeof( (( type * ) 0)→field ) *__mptr = ( ptr );

(type *)( (char *)__mptr — offsetof( type , field ) );})

……………………………………………………………………………

lets understand it by a real world example:

Assume you have 3 containers, c1 having flower, c2 having clothes, c3 having pen and I ask you which container have pen.

So I know that there are some containers(user defined structure — Dev) and one of them have pen(field) but I don’t know in which container(ie.. address of struct Dev).

So you( ie.. container_of() ) will tell me address of c3( struture Dev) which have pen( filed of the structure) .This is how exactly container_of() works.

--

--

EmbLogic RCD Labs
0 Followers

EmbLogicTM is a technology design house and professional training company, providing research, competency development and customised training solutions.