container_of是谁发明的,真是个天才!!!

This commit is contained in:
建峰 2024-09-01 17:38:44 +08:00
parent 7f42d43cd2
commit 42d305eabe
7 changed files with 30 additions and 3 deletions

View File

@ -7,5 +7,18 @@
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
// [warring] offsetof is redefined in stddef.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) );})
#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) );})
#endif

View File

@ -58,6 +58,8 @@ struct _copper_cash *copper_cash_new(double width, double height, double radius)
{
return NULL;
}
cc->self = cc;
cc->price = 100;
// set parent
cc->shape = shape;

View File

@ -9,6 +9,8 @@
struct _copper_cash
{
struct _copper_cash *self;
struct _shape *shape;
struct _rect *rect;
struct _circle *circle;

View File

@ -11,8 +11,11 @@ double rect_area(void *self, void *parent)
void rect_draw(void *self, void *parent)
{
struct _rect *pthis = (struct _rect *)parent;
pthis->shape->vtb.draw(self, NULL);
// struct _rect *pthis = (struct _rect *)parent;
// pthis->shape->vtb.draw(self, NULL);
struct _rect *pthis = container_of(parent, struct _rect, self);
pthis->shape->vtb.draw(pthis, NULL);
}
double _rect_area(void *self, void *parent)
@ -50,6 +53,8 @@ struct _rect *rect_new(double width, double height)
{
return NULL;
}
rect->self = rect;
rect->width = width;
rect->height = height;
// set parent

View File

@ -7,7 +7,8 @@
struct _rect
{
int invalid;
// int invalid;
struct _rect *self;
// super
struct _shape *shape;

View File

@ -56,6 +56,8 @@ struct _shape *shape_new(void)
{
return NULL;
}
shape->self = shape;
static struct _virtual_table vtb = {
.area = (double (*)(void *self, void *parent))_shape_area,
.draw = (void (*)(void *self, void *parent))_shape_draw

View File

@ -17,6 +17,8 @@ struct _virtual_table
struct _shape
{
struct _shape *self;
struct _virtual_table vtb;
};