From: José Fonseca Date: Thu, 1 May 2008 12:52:05 +0000 (+0900) Subject: Add Brian's explanation for inheritance in C. X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=073bb94a4150d7b3c78ea5420383cb7ed8f97566;p=mesa.git Add Brian's explanation for inheritance in C. --- diff --git a/src/gallium/README.portability b/src/gallium/README.portability index ab0c1978476..18a97f449b4 100644 --- a/src/gallium/README.portability +++ b/src/gallium/README.portability @@ -24,6 +24,7 @@ headers in general, should stricly follow these guidelines to ensure * Don't use variable number of macro arguments. Use static inline functions instead. +* Don't use C99 features. = Standard Library = @@ -42,3 +43,67 @@ portable way. * Use the functions/macros in p_debug.h. * Don't include assert.h, call abort, printf, etc. + + += Code Style = + +== Inherantice in C == + +The main thing we do is mimic inheritance by structure containment. + +Here's a silly made-up example: + +/* base class */ +struct buffer +{ + int size; + void (*validate)(struct buffer *buf); +}; + +/* sub-class of bufffer */ +struct texture_buffer +{ + struct buffer base; /* the base class, MUST COME FIRST! */ + int format; + int width, height; +}; + + +Then, we'll typically have cast-wrapper functions to convert base-class +pointers to sub-class pointers where needed: + +static inline struct vertex_buffer *vertex_buffer(struct buffer *buf) +{ + return (struct vertex_buffer *) buf; +} + + +To create/init a sub-classed object: + +struct buffer *create_texture_buffer(int w, int h, int format) +{ + struct texture_buffer *t = malloc(sizeof(*t)); + t->format = format; + t->width = w; + t->height = h; + t->base.size = w * h; + t->base.validate = tex_validate; + return &t->base; +} + +Example sub-class method: + +void tex_validate(struct buffer *buf) +{ + struct texture_buffer *tb = texture_buffer(buf); + assert(tb->format); + assert(tb->width); + assert(tb->height); +} + + +Note that we typically do not use typedefs to make "class names"; we use +'struct whatever' everywhere. + +Gallium's pipe_context and the subclassed psb_context, etc are prime examples +of this. There's also many examples in Mesa and the Mesa state tracker.