/* Takes a pointer to a member variable and computes pointer to the structure
that contains it. 'type' is type of the structure, not the member. */
#define
nn_cont
(
ptr
,
type
,
member
) \
(
ptr
? ((
type
*) (((
char
*)
ptr
) -
offsetof
(
type
,
member
))) :
NULL
)
這個宏是經過知道ptr的地址,這個地址也是member的地址,使用offsetof計算menber的偏移量,ptr-member的偏移量得到
type結構體變量的地址。
在nanomsg代碼中,
for
(
it
=
nn_list_begin
(&
self
.
socktypes
);
it
!=
nn_list_end
(&
self
.
socktypes
);
it
=
nn_list_next
(&
self
.
socktypes
,
it
)) {
socktype
=
nn_cont
(
it
,
struct
nn_socktype
,
item
);
......
}
socktypes 是個鏈表,保存着結構體
nn_socktype 的 item 成員,因此it指向的是成員item的地址,經過item的地址得到
結構體
nn_socktype 的變量
socktype
。