Kernel - container_of()

숲사람·2022년 7월 20일
0

Linux Kernel

목록 보기
8/10

어떤 구조체 내의 내부 포인터를 알고 있을때, 해당 구조를 포함하는 상위 구조체의 정보를 참조할때 유용한 Kernel API이다.

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

3개의 매개변수

  • ptr : 현재 알고있는 구조체내의 멤버 포인터
  • type : ptr을 포함하고 있는 구조체의 원형 (알고싶은 구조체)
  • member : type구조체에서 ptr의 멤버명 (알고싶은 구조체에서 ptr멤버명)

#define container_of(멤버포인터, 구조체 원형, 구조체 멤버 종류)

사용방법 예시

/* 
 * member가 type의 포인터 멤버일때 container_of를 어떻게 사용하는가????
 **/

## 1
#include <stdio.h>

#define offsetof(type, member) ((size_t) &((type *)0)->member)

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

struct te {
	int t;
} data;

struct type
{
	char ttt;
	int *member;
	struct te *d;
} con;

int main()
{
	con.d = &data;
	printf("%p\n", &con);
	printf("%p\n", container_of(&(con.member), struct type, member));

	printf("%p\n", &con);
	printf("%p\n", container_of(&(con.d), struct type, d));

	return 0;
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글