mirror of
https://gitee.com/apaki/cmake_demo.git
synced 2025-05-17 20:01:36 +08:00
container_of是谁发明的,真是个天才!!!
This commit is contained in:
parent
7f42d43cd2
commit
42d305eabe
@ -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
|
||||
|
@ -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;
|
||||
|
@ -9,6 +9,8 @@
|
||||
|
||||
struct _copper_cash
|
||||
{
|
||||
struct _copper_cash *self;
|
||||
|
||||
struct _shape *shape;
|
||||
struct _rect *rect;
|
||||
struct _circle *circle;
|
||||
|
@ -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
|
||||
|
@ -7,7 +7,8 @@
|
||||
|
||||
struct _rect
|
||||
{
|
||||
int invalid;
|
||||
// int invalid;
|
||||
struct _rect *self;
|
||||
|
||||
// super
|
||||
struct _shape *shape;
|
||||
|
@ -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
|
||||
|
@ -17,6 +17,8 @@ struct _virtual_table
|
||||
|
||||
struct _shape
|
||||
{
|
||||
struct _shape *self;
|
||||
|
||||
struct _virtual_table vtb;
|
||||
};
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user