C++中二维浮点数组的序列化和反序列化

Serialization and deserialization of two dimensional float array in C++

本文关键字:数组 序列化 反序列化 二维 C++      更新时间:2023-10-16

我有一个结构:

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

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

有人能给我一些提示吗?

如果你留在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;
}

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

*Jost

最好使用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()