This is the mail archive of the
guile@cygnus.com
mailing list for the Guile project.
Re: Casting a pointer to a structure
- To: guile@cygnus.com
- Subject: Re: Casting a pointer to a structure
- From: Marius Vollmer <mvo@zagadka.ping.de>
- Date: 20 Jul 1999 19:27:50 +0200
- References: <199907180151.UAA04587@savonarola.red-bean.com> <p2td7xoearn.fsf@grapefruit.zrz.tu-berlin.de>
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?