1

我有一个结构:

struct Desc {
    int rows;
    int cols;
}

和二维浮点数组。

我需要data通过网络传输结构。如何正确序列化/反序列化?

这就是我现在所做的:

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

但我不确定这是否是正确的方法。

有人可以给我一些提示如何做到这一点吗?

4

2 回答 2

1

如果你留在 C++ 中并且想要提高效率,我会使用Boost Serialization - 否则 JSON 可能是你的朋友。我改编了演示以将您的结构序列化为文件-但基本上它向/从流中写入/读取。

#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;
}

注意:我没有检查这个例子是否有效。

*约斯特

于 2013-07-18T10:59:22.623 回答
0

最好使用 NOT 二进制序列化。例如:纯文本(std::stringstream)、JSON、XML 等。

С++ 示例:

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()
于 2013-07-18T10:52:58.540 回答