How to read a C++ class from file into memory

Daniel Keep daniel.keep.lists at gmail.com
Thu Mar 22 17:19:19 PDT 2007



David Finlayson wrote:
> I am coming from Python to D, so forgive my limited C/C++ knowledge.

Don't worry; I'd be inclined to think it's a good thing :3

> What is the idiomatic way to read a heterogeneous binary structure in D? 
> 
> In my C++ book, it shows examples of defining a class or struct with the appropriate types and then passing a pointer to this class to fread().

For my money, that's a bad idea because the binary representation of a
struct or object isn't necessarily the same on different machines or
even same machine, different operating system.

Quick example: real is a different size on Windows to Linux (IIRC).

> However, in Java or Python I could just read the types directly from a binary stream (including the padding bytes associated with the structure on disk).
> 
> How should I do this in D?
> 
> I did see this post:
> 
> http://www.digitalmars.com/webnews/newsgroups.php?art_group=digitalmars.D.learn&article_id=6071
> 
> Note that I ultimately want to store these data back into classes where I can work with it.
> 
> Thanks,
> 
> David

The nice thing about Python is the pickle protocol.  That's what I
assume you were using.  Since Python can interactively inspect objects
to find out what data is attached to them, this is really easy.  It's
also nice because pickle isn't blind: it will serialise things in a
predictable format based on type, not on in-memory layout.

So you can dump a bunch of Python objects to a file, send it to another
machine, and read them back out again.

In D, we're kinda-sorta there.  The way I'm solving this is using the
.tupleof property of structures.  For example:

struct Point { double x, y; }

{
    Point pt;
    foreach( member ; pt.tupleof )
        member = 0.0;
}

At which point, pt.x = pt.y = 0.  Combining this with templated
functions lets you write out or read in any structure you please.

Note: I haven't tried *any* of this with classes, because my feeling is
that classes are often much more complex than structures (which are just
plain old data, clumped together), plus they're far more likely to have
references to other stuff; then what do you do?

I thought about including some code from my serialisation library, but
it tends to be "all or nothing".  Plus, this was written for a research
project, and I'm not sure who *actually* owns the code (me or the uni) X_X.

Anyway, hope this helps :)

	-- Daniel

-- 
int getRandomNumber()
{
    return 4; // chosen by fair dice roll.
              // guaranteed to be random.
}

http://xkcd.com/

v2sw5+8Yhw5ln4+5pr6OFPma8u6+7Lw4Tm6+7l6+7D
i28a2Xs3MSr2e4/6+7t4TNSMb6HTOp5en5g6RAHCP  http://hackerkey.com/


More information about the Digitalmars-d-learn mailing list