gpt4 book ai didi

c++ - C++中二维float数组的序列化与反序列化

转载 作者:行者123 更新时间:2023-11-28 07:30:58 50 4
gpt4 key购买 nike

我有一个结构:

struct Desc {
int rows;
int cols;
}

和二维 float 组。

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

这就是我现在做的:

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 可能是你的 friend 。我改编了 demo用于将您的结构序列化为文件 - 但基本上它写入/读取流。

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

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

*约斯特

关于c++ - C++中二维float数组的序列化与反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17721186/

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com