rt_container_of 原理(通过结构体成员地址反推出结构体地址,进而访问结构体中的所有成员)

#include <stdio.h>
#include <string.h>

/* 返回 ptr 所在结构体的指针 */
#define rt_container_of(ptr, type, member) \
    ((type *)((char *)(ptr) - (unsigned long)(&((type *)0)->member)))

struct rt_list_node
{
    struct rt_list_node* next;                          /**< point to next node. */
    struct rt_list_node* prev;                          /**< point to prev node. */
};
typedef struct rt_list_node rt_list_t;                  /**< Type for lists. */

struct _test_struct
{
    const char* name;
    int age;
    int weight;
};

int main(int* argc, int* argv[])
{
    struct _test_struct student;

    student.age = 21;
    student.weight = 135;
    student.name = "tzy";

    const char** student_name = &student.name;

    struct _test_struct* _struct = rt_container_of(student_name, struct _test_struct, name);
    if (!strcmp(_struct->name, student.name))
    {
        printf("test success--------------------\n");
        printf("_struct name = %s\n", _struct->name);
        printf("student name = %s\n", student.name);
    }
    else
    {
        printf("test fail");
        printf("_struct name = %s\n", _struct->name);
        printf("student name = %s\n", student.name);
    }

    int* student_age = &student.age;

    _struct = rt_container_of(student_age, struct _test_struct, age);
    if (_struct->age == student.age)
    {
        printf("test success-------------------\n");
        printf("_struct age = %d\n", _struct->age);
        printf("student age = %d\n", student.age);
    }
    else
    {
        printf("test fail");
        printf("_struct age = %d\n", _struct->age);
        printf("student age = %d\n", student.age);
    }

    return 1;
}

上一篇:如何在PHP中正确使用WooCommerce订阅API?


下一篇:【CVPR 2019】 论文阅读:3D human pose estimation in video with temporal convolutions and semi-supervised tr