问题
I have a structure:
struct Desc {
int rows;
int cols;
}
and two dimensional float array.
I need to transfer the structure and data through the network. How to serialize/deserialize it correctly?
This is what I do now:
Desc desc;
desc.rows = 32;
desc.cols = 1024;
float data[rows][cols];
// setting values on array
char buffer[sizeof(Desc)+sizeof(float)*desc.rows*desc.probes];
memcpy(&buffer[0], &desc, sizeof(Desc)); // copying struct into the buffer
memcpy(&buffer[0]+sizeof(Desc), &data, sizeof(float)*rows*probes); // copying data into the buffer
but I'm not sure if this is a correct approach.
Can someone give me some hints how to do this?
回答1:
If you stay in C++ and want to be efficient I would use Boost Serialization - otherwise JSON might be your friend. I adapted the demo for serializing your struct to a file - but basically it writes/reads to/from streams.
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
struct Desc {
int rows;
int cols;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & rows;
ar & cols;
}
public:
Desc()
{
rows=0;
cols=0;
};
};
int main() {
std::ofstream ofs("filename");
// prepare dummy struct
Desc data;
data.rows=11;
data.cols=22;
// save struct to file
{
boost::archive::text_oarchive out_arch(ofs);
out_arch << data;
// archive and stream closed when destructors are called
}
//...load struct from file
Desc data2;
{
std::ifstream ifs("filename");
boost::archive::text_iarchive in_arch(ifs);
in_arch >> data2;
// archive and stream closed when destructors are called
}
return 0;
}
Note: I've not checked if this example works.
*Jost
回答2:
It is better to use NOT binary serialization. For example: plain text(std::stringstream), JSON, XML etc.
С++ example:
int width = 10;
int height = 20;
float array[height][width];
std::stringstream stream;
stream << width << " " << height << " ";
for (int i = 0; i < height; ++i)
{
for (int j = 0; j < width; ++j)
{
stream << array[i][j] << " ";
}
}
std::string data = stream.str();
// next use the data.data() and data.length()
来源:https://stackoverflow.com/questions/17721186/serialization-and-deserialization-of-two-dimensional-float-array-in-c