:: Re: [DNG] Experiencing with GtkBuil…
Página superior
Eliminar este mensaje
Responder a este mensaje
Autor: Rainer Weikusat
Fecha:  
A: dng
Asunto: Re: [DNG] Experiencing with GtkBuilder
Steve Litt <slitt@???> writes:
> On Mon, 23 Nov 2015 06:45:54 -0500
> Hendrik Boom <hendrik@???> wrote:
>> There is a well-known hack in C wheereby you rely on C allocating
>> fields of structures independently of later fields.
>>
>> Thus with
>> struct foo{char c, int d, float e,}
>> and
>> struct bar{char c, int d,}
>>
>> (forgive me if I need semicolons here; I've used too many languages
>> in the alst year to remember the surface syntax)
>>
>> you can rely on c and d having the same offsets in both structures,
>> and so you can happily cast between pointers to foo and bar as long
>> as you don't mess with e.
>>
>> And, of course, you can have a pointer to a table of methods as the
>> first entry in all of these structures.
>
> Aren't C unions the "official" way to deal with these situations?


Absolutely not. A 'union' is a record with fields of different type all
allocated at the same address. The usual way of dealing with this would
be to put a struct bar into a struct foo, ie,

struct foo {
       struct bar parent;
       float e;
};


in order to avoid duplicating the definition of bar. Derived classes
aren't usually supposed to access data members of base classes directly,
hence, 'explicit' access to data members often isn't needed and virtual
methods will usually be invoked via (inline) wrapper functions
encapsulating the vtable lookup, eg, the

static int calc(struct something *sth)
{
    return sth->vt->calc(sth);
}


in the example I posted. The only important thing is that the nested
struct is organized such that a pointer to the most derived structure is
always also a valid pointer to any of the superclasses.

This idea isn't exactly new. AFAIK, it was first publically used to
implement Vnodes for SunOS in 1986 and the basic concept goes back to
the so-called 'character device switch' in 1970s 'research UNIX(*)' (I
could provide the source for that if someone wants it). If the "warring
Gnomes" (self-description) couldn't implement it, this would seem to be
their problem.