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 <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <assert.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 #endif

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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