I have the following struct defining data returned from a collection of HID device reports:
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:
// 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). 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.
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).
What’s an appropriate way to get the binary data from my std::vector<unsigned char> to my DevInfo struct?
There’s nothing stopping you from using either
std::memcpyorstd::copyto populate an object from binary data stored in avector, as long as it is a trivially-copyable standard-layout type:However, in your case it appears that you have a non-trivial data member (assuming that
stringrefers tostd::string), so you can’t do either of these things.