0

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.

9
  • What do you mean by the "byte stream"? What do you intend to do with it? Commented Mar 25, 2012 at 22:38
  • 1
    Check out some serialization frameworks like msgPack or Thrift. The approach you describe here will not work for strings or complex data structures. Commented Mar 25, 2012 at 22:41
  • @OliCharlesworth: I need the byte streams to do some calculation (for Rabin's Algorithm). Commented Mar 25, 2012 at 22:46
  • @DvirVolk: But the above code worked for object one. As far as I know serialization in C++ does not work for vectors or lists. Commented Mar 25, 2012 at 22:46
  • 2
    your code may have worked by accident because you deserialized it in the same process space, so all the pointers remained in place. but you will never be able to serialize it across processes. Commented Mar 25, 2012 at 22:53

1 Answer 1

2

You do realize that you're writing the address of one, right? Basically what you've written is the equivalent of:

NodeEntry** doublePtr = &one;
oner = *doublePtr;

If you wanted to write the contents of the object, you'd pass one to write and sizeof(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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.