If o is an object and m is a member of the object, and you know the adress of m, can you then tell the adress of o?
Printable View
If o is an object and m is a member of the object, and you know the adress of m, can you then tell the adress of o?
you can use the offsetof macro, but it won't work for members that are references.
Nor will it work if the member is a function, of course.
Furthermore, offsetof may only be used for PODs, just like the necessary pointer casts are valid only for PODs.
POD (Plain Ol' Data) types are, succinctly put, those that can be written in C. (That's not quite accurate, but sufficiently so.)
It CAN be done, but as explained, there are MANY restrictions, the most obvious covered above.
Linux (and related) have a macro to get a base-pointer from a member of a function, like this:
--Code:#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (char *)__mptr - offsetof(type,member) );})
Mats
The most portable way to do it would be if you had a pointer to a member function -- in which case you could just return this -- or make m itself have a member pointing to o. Or just have a pointer to o in the first place.
Basically, in any situation where you can assume that the pointer you actually does point to a member of a struct, and you find you need a pointer to that struct but don't have one, you're facing a design error. You should have provided a pointer to the struct to the component in question in the first place.
In most situations, you can't assume that you've got a member.