How to read a C++ class from file into memory
Jarrett Billingsley
kb3ctd2 at yahoo.com
Fri Mar 23 05:32:28 PDT 2007
"David Finlayson" <david.p.finlayson at gmail.com> wrote in message
news:etvmlg$1auh$1 at digitalmars.com...
> For the moment, I just want to understand the key part of your Deserialize
> function.
>
> The secret sauce is in this line (and others like it):
>
> s.readExact(strptr, char.sizeof * len)
>
> where s is a file stream. It looks like with this method, it is only
> possible to read a single variable or an array of the same type (as you
> are doing here). Is it possible to send a pointer to a struct and read
> THAT in from the stream? If so, how does it handle padding bytes? I know
> there is an align() attribute for structs that might apply here.
Yes, as you've seen in the other post, you can do that. As for alignment
issues, that's up to your structure to know the layout of your data. Say
you know the format is something like:
Header structure:
0x0000 4 bytes: Magic number
0x0004 2 bytes: Version
0x0005 1 byte: Flags
0x0006 1 byte: (padding)
0x0008 24 bytes: Comments
0x0020 4 bytes: offset in file to some table
0x0023 4 bytes: (reserved)
--------------------------
Total: 40 bytes
So you could write your structure like this. Notice we use "align(1)" on
the structure to signal to the compiler that the members should be packed in
as tightly as possible. This way we have complete control over how the data
is laid out.
align(1) struct Header
{
uint magic;
ushort version;
ubyte flags;
ubyte _padding1;
char[24] comments;
uint tableOffset;
uint _reserved;
}
// For good measure
static assert(Header.sizeof == 40);
That static assert is there to make sure that the structure's size matches
the calculated size of the header, and to make sure that we don't
inadvertently change the header struct and mess things up. Of course, if
the header is a variable length, that assert probably wouldn't be there.
More information about the Digitalmars-d-learn
mailing list