Using boost serialization to send a vector.

Started by
1 comment, last by hplus0603 11 years, 6 months ago
I've run into a real problem with regards to sending serialized vectors over a socket. A simplified example of what I'm doing:

Server:

#include <boost/serialization/vector.hpp>


struct someObject
{
int i;
template <class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & i;
}
}

struct OutStream
{
std::vector <someObject> someVector;

template <class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & someVector;
}
}outStream;

// Another part of the code
outStream.someVector.swap(someOtherVector);

// Serialise
std::stringstream archive_stream;
boost::archive::text_oarchive archive(archive_stream);
archive << outStream;


// Send
sendto(ServerSocket, archive_stream.str().c_str(), strlen(archive_stream.str().c_str())...


Client:

#include <boost/serialization/vector.hpp>

struct someObject
{
int i;
template <class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & i;
}
}

struct InStream
{
std::vector <someObject> someVector;

template <class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & someVector;
}
}inStream;

// Another part of the code
// Deserialize
archive_stream << temp;
boost::archive::text_iarchive archive(archive_stream);
ZeroMemory(&inStream, sizeof(inStream));
archive >> inStream;

someOtherVector.swap(inStream.someVector);


However when I run this, on the server side, either it doesn't send proberly(lots of blank variables) or it says
Expression:vector iterator not dereferencable[/quote]

If it would help I can upload the whole source code (it's not that large). Any help is much appreciated!

Thanks,
Rowan.
Advertisement
I would recommend using a more specific type than int in your marshalling code. The meaning of int can change between platforms.

This line:

ZeroMemory(&inStream, sizeof(inStream));

looks questionable. I didn't see the definition of that function, but maybe you don't need to call that function.

If you are interested in switching to binary serialization, I could be of more help.
ZeroMemory() is the same thing as memset() with a 0 argument. You can only use it on POD (plain old data) values. Your InStream struct is not POD, as it contains a std::vector container.
What you probably want is instead:

inStream.someVector.clear();


Or, the idiomatic:

std::vector<someObject>().swap(inStream.someVector);


which is guaranteed to clean up any allocated memory right away, rather than just marking it as "use this next time something goes into this vector."
enum Bool { True, False, FileNotFound };

This topic is closed to new replies.

Advertisement