简体   繁体   中英

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:

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::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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM