C question
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?
Comments
on 2005-12-06 6:39:55.0, tom commented:
Good question. I have no idea. It's been a few years since I had to deal with C -- I've grown soft & weak.
and, further, on 2005-12-06 11:57:41.0, ben wolfson commented:
Answer: yes. It seems one can write brief programs to test these things.
and, further, on 2005-12-06 0:00:14.0, ben wolfson commented:
In retrospect, I think this is more or less exactly how Python implements its built-in objects at the C level.
and, further, on 2005-12-07 20:32:13.0, tweedledopey commented:
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).