c++ - 将任何数据类型序列化为 vector<uint8_t> - 使用 reinterpret_cast?

标签 c++ templates serialization network-programming

我没有在搜索中找到任何直接相关的内容,所以如果这是重复的,请原谅。

我要做的是通过网络连接序列化数据。我的方法是将我需要传输的所有内容转换为 std::vector< uint8_t >并在接收方将数据解压缩到适当的变量中。我的方法是这样的:

template <typename T>
inline void pack (std::vector< uint8_t >& dst, T& data) {
    uint8_t * src = static_cast < uint8_t* >(static_cast < void * >(&data));
    dst.insert (dst.end (), src, src + sizeof (T));
}   

template <typename T>
inline void unpack (vector <uint8_t >& src, int index, T& data) {
    copy (&src[index], &src[index + sizeof (T)], &data);
}

我用的是什么

vector< uint8_t > buffer;
uint32_t foo = 103, bar = 443;
pack (buff, foo);
pack (buff, bar);

// And on the receive side
uint32_t a = 0, b = 0;
size_t offset = 0;
unpack (buffer, offset, a);
offset += sizeof (a);
unpack (buffer, offset, b);

我担心的是

uint8_t * src = static_cast < uint8_t* >(static_cast < void * >(&data));

行(我理解为与 reinterpret_cast 相同)。有没有更好的方法来实现这一点而无需双重 Actor ?

我天真的方法是只使用 static_cast< uint8_t* >(&data)失败了。我有 been told in the pastreinterpret_cast不好。所以我想尽可能避免它(或我目前拥有的结构)。

当然,总有uint8_t * src = (uint8_t *)(&data) .

建议?

最佳答案

我的建议是忽略所有告诉您 reinterpret_cast 不好的人。他们告诉你这很糟糕,因为采用一种类型的内存映射并假装它是另一种类型通常不是一个好习惯。但在这种情况下,这正是您想要做的,因为您的全部目的是将内存映射作为一系列字节传输。

它比使用双 static_cast 要好得多,因为它充分详细说明了您正在采用一种类型并有目的地假装它是另一种类型的事实。这种情况正是 reinterpret_cast 的用途,将它与 void 指针中介一起使用只会模糊你的意思,没有任何好处。

此外,我相信您已经意识到这一点,但请注意 T 中的指针。

关于c++ - 将任何数据类型序列化为 vector<uint8_t> - 使用 reinterpret_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3161342/

相关文章:

java - 如何序列化 HttpHandler 类中的对象

c++ - 在 C++ 中将 hdf5 文件读取到动态数组

c++ - 为什么 enable_if 不能在这里工作?

c# - 无法访问已关闭的流

java - Wicket:<body> 中模板化的 javascript?

html - 布局以填充除 Extjs 中的导航栏之外的所有浏览器窗口

python - Pickle Python 序列化

c++ - 如何在 C++11 中将 lambda 表达式存储为类的字段?

c++ - 保护内容文件

c++ - 如何聚焦或选择一个项目?