Re: Converting from C style struct offset to C++ style member pointer
In article <xn0izvx1q5t6y1h00d@news.astraweb.com>
"Asger Joergensen" <Junk@Asger-P.dk> writes:
Hi Marcel
%
Marcel M?ller wrote:
When I get a struct offset from a C style API as int. I.e.:
struct S
{ int I1;
double D1;
int I2;
};
int offset = offsetof(S, I2);
Now in C++ code I would like to convert this offset to a type safe C++ member
pointer of type int S::*. Older gcc versions simply accepted a cast, newer
version reject the cast.
I am curious, where do you use this offsetof I mean in what situations are
you using it ?
It is a not uncommon usage in embedded work close to the hardware.
Interface* interface = (Interface*) 0xdeadbeef;
// do stuff with the pointer
The main case I recall from back when I was using such things
involved runtime confirmation that a struct definition was correctly
overlaying a memory-mapped interface.
if ( offsetof(Interface, command_port) != 0x005 )
complain_that_world_is_wrong();
Of course, this was just confirmation testing in in-house builds.
I may have had other uses for it, but they aren't coming to mind.
I've been programming for 15+ years and it is the first time I see this
offsetof define, usually I just cast to the struct name and then address
it's members by their name, leaving the offset part to the compiler.
Would you be so kind and explain the need and give a couple of small examples ?
Thanks in advance
Best regards
Asger-P
http://Asger-P.dk/software
Standards were invented, so we all can have our own.
--
Drew Lawson
I only came in search of answers, never planned to sell my soul
I only came in search of something left that I could call my own