[英]Populate a struct from data in a std::vector<unsigned char>
I have the following struct defining data returned from a collection of HID device reports: 我有以下结构定义从HID设备报告的集合返回的数据:
struct DevInfo {
char unknown[0x40];
string name;
char unknown2[0x240];
};
It's currently incomplete, but that's irrelevant to my question. 目前尚不完整,但这与我的问题无关。 Previously, I was populating an instance of this struct using memcpy
to copy data from a char array, like so: 以前,我使用memcpy
填充此结构的实例以从char数组复制数据,如下所示:
// get data from HID device
unsigned char *response = sendCommand(DEV_REPORT);
// Copy to struct
DevInfo *info;
memcpy(&info, &response[0], sizeof(response));
// Output name
cout << "Name: " << info->name << "\n";
This worked, except that I was apparently doing something that I shouldn't (returning a reference to a char array from a function). 这行得通,除了我显然在做我不应该做的事情(从函数返回对char数组的引用)。 So, after researching, I switched to a safer std::vector<unsigned char>
approach, but now I can't use memcpy
to populate the data in the struct. 因此,在研究之后,我切换到了更安全的std::vector<unsigned char>
方法,但是现在我无法使用memcpy
来填充结构中的数据。
Someone advised me to use std::vector<DevInfo>
instead of std::vector<unsigned char>
, but the problem with that is there are several different reports that can be retrieved from the HID device, so I need to be able to populate different structs using the same function ( sendCommand
). 有人建议我使用std::vector<DevInfo>
代替std::vector<unsigned char>
,但是问题是可以从HID设备中检索到几种不同的报告,因此我需要能够使用相同的函数( sendCommand
)填充不同的结构。
What's an appropriate way to get the binary data from my std::vector<unsigned char>
to my DevInfo
struct? 从我的std::vector<unsigned char>
到我的DevInfo
结构中获取二进制数据的合适方法是什么?
There's nothing stopping you from using either std::memcpy
or std::copy
to populate an object from binary data stored in a vector
, as long as it is a trivially-copyable standard-layout type: 只要它是普通可复制的标准布局类型,就不会阻止您使用std::memcpy
或std::copy
从存储在vector
二进制数据填充对象:
DevInfo info;
std::vector<char> response = get_response();
assert(response.size() == sizeof info);
std::copy(response.begin(), response.end(), reinterpret_cast<char*>(&info));
std::memcpy(&info, &response[0], sizeof info); // C++11 allows response.data()
However, in your case it appears that you have a non-trivial data member (assuming that string
refers to std::string
), so you can't do either of these things. 但是,在您的情况下,您似乎有一个非平凡的数据成员(假设该string
引用了std::string
),因此您将无法执行上述任何一项操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.