This is the mail archive of the guile@cygnus.com mailing list for the Guile project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: Casting a pointer to a structure


Jost Boekemeier <jostobfe@calvados.zrz.TU-Berlin.DE> writes:

> Hi,
> 
> does anyone know if it is possible to cast a pointer to
> a structure into a pointer to the first element of a substructure?
> 
> For example:
> 
> struct env_funcs {
>   int something;
> }
> struct x {
>   struct *env_funcs;
>   int something;
> }
> struct m {
>   struct x x;
>   int something;
> }
> 
> Now is it possible to cast a pointer to m into a pointer to a pointer
> to struct env_funcs?

Can't you do this?

    struct m *ptr1 = ...;
    struct env_funcs **ptr2 = &(ptr1->x.env_funcs);

Given that x and env_funcs are (guaruanteed/likely) to have a zero
offset in their respective structures, this should be reduced by the
compiler to a simple cast without any run-time computation.  Let's
call this `down-casting'.  It also works for members that don't have a
zero offset, of course.

The more interesting case is `up-casting', I think, when you go from a
contained member to the containing structure object.  Like

    struct env_funcs **ptr1 = ...;
    struct m *ptr2 = (struct m *)ptr1;

Is this safe too?  How can this be safely generalized to
non-zero-offset members?

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]