I need to get the byte stream of an object in C++.
I could not find a way to do this without using serialization.
NodeEntry *one = new NodeEntry("mani", 34, 56.3);
ofstream rofs("result.ros", ios::binary);
rofs.write((char *)&one, sizeof(one));
rofs.close();
// now we read the file into object!!
ifstream ifsr("result.ros", ios::binary);
NodeEntry *oner;
ifsr.read((char *)&oner, sizeof(oner));
Is there any other workaround? I don’t want to send this object through the network or store it on hard disk. I just want to get the byte stream of object one without actually creating the file.
In other word I need to create a byte stream of object one and store it somewhere (like in an ostream), then passing these bytes to another method and re-construct the object from these bytes.
I would appreciate if you give me a hint on this.
You do realize that you’re writing the address of
one, right? Basically what you’ve written is the equivalent of:If you wanted to write the contents of the object, you’d pass
onetowriteandsizeof(NodeEntry), but as Dvir Volk mentions, this won’t work right (or at least probably not how you want it to) with anything that contains a pointer.Anyway, I like Google’s Protocol Buffers for serializing objects. It’s a far more robust solution to your problem.
Also, “byte stream” makes no sense… do you mean the raw memory of the object in bytes?