reinterpretcast help . from struct to stream and vice-versa


I have a stream to store and retrieve values from - to an structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
My_structure {
 int A;
 double B;
};

put (My_structure &value) {
     const char * buffer ;
     buffer = reinterpret_cast<const char*> (&value);
     the_stream.write(buffer,sizeof value);
}

get (My_structure & value) {
    char * buffer ;
    buffer = reinterpret_cast<char*> (&value);
    the_stream.get(buffer, sizeof value);
    value = *reinterpret_cast<My_structure*> (buffer);

}

This compile but I get strange values.... (the tellg and tellp are well pointed to zero before starts the get's)
I dont know how to write this last line (value = ) to get the right values...

Any help would be appreciated.
Line 14 makes the buffer point to your structure, so when line 15 goes to copy data there, it'll be in your structure. You don't even need line 16.
So the "reinterpret" is done when the_stream.get(buffer, sizeof value); is executed ?
It is like 'magic' ????

After the_stream.get(buffer, sizeof value) is exectude,
buffer keeps being a char * , isn't ?

So I dont see the link betwen 'buffer' and 'value'. I dont know how is it possible that 'value 'can get the value 'reinterpreting the bytes'...
How does C++ it ?
You're reinterpret_castint one kind of pointer to another (which can be done just fine with a c-style cast), you're not actually reinterpret_casting the class object to a character pointer (which would not work!). Remember, pointers just point to a single memory address, they aren't actually the data itself. Think of pointers as type-safe unsigned longs.
Last edited on
Topic archived. No new replies allowed.