将结构转换为字节的向量 [英] Convert a struct to vector of bytes

查看:198
本文介绍了将结构转换为字节的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的c ++应用程序中,我有这个结构

In my c++ application I have this struct

typedef struct 
{
int a;
int b;
char *c
}MyStruct

p>

and I have this instance:

MyStruct s;

也有这个定义:

vector<byte> buffer;

我想将s结构体插入到缓冲区向量。

I would like to insert\convert the "s" struct to the buffer vector.

在c ++中做最好的方法是什么?

what is the best way to do it in c++?

感谢

推荐答案

最好的方法是使用范围拷贝构造函数和一个低级别的转型来检索指向结构的内存的指针:

The best way is by using the range copy constructor and a low-level cast to retrieve a pointer to the memory of the structure:

auto ptr = reinterpret_cast<byte*>(&s);
auto buffer = vector<byte>{ptr, ptr + sizeof(s)};

这篇关于将结构转换为字节的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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