C ++中的二维浮点数组的序列化和反序列化 [英] Serialization and deserialization of two dimensional float array in C++

查看:223
本文介绍了C ++中的二维浮点数组的序列化和反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构:

struct Desc {
    int rows;
    int cols;
}

和二维浮点数组。

我需要通过网络传输结构和数据。如何正确地对其进行序列化/反序列化?

I need to transfer the structure and data through the network. How to serialize/deserialize it correctly?

这就是我现在要做的:

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?

推荐答案

如果您使用C ++并想提高效率,我会使用加强序列化-否则JSON可能是您的朋友。我修改了演示来序列化您的

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

这篇关于C ++中的二维浮点数组的序列化和反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆