Suppose you had some declarations:
typedef struct {
int datum;
void (*func) (void* s, int count, ...);
} A;
typedef struct {
int datum;
void (*func) (void* s, int count, ...);
int anotherdatum;
} B;
and a pointer to a B struct (call it bp
). You pass bp
to a function expecting a pointer to an A
, so you typecast it: somefunc((A*)bp);
. Call the formal parameter to somefunc foo
. That's cool (as I understand it), because the two structs share the same initial layout. Within somefunc
, the following line: foo->func((void*)foo, 0);
. Within the particular function that is bp
's func
, s
is cast to be a pointer to B
. My question: will s
be able to access anotherdatum
?
Good question. I have no idea. It's been a few years since I had to deal with C -- I've grown soft & weak.
Posted by: tom | December 06, 2005 at 06:39 AM
Answer: yes. It seems one can write brief programs to test these things.
Posted by: ben wolfson | December 06, 2005 at 11:57 AM
In retrospect, I think this is more or less exactly how Python implements its built-in objects at the C level.
Posted by: ben wolfson | December 06, 2005 at 12:00 PM
It makes sense that it would allow you to access bp->anotherdatum. My guess, though, is that it is one of those "undefined" behaviours that always works out right (i.e., if there were a lot of memory usage, it might not work out well).
Posted by: tweedledopey | December 07, 2005 at 08:32 PM