[英]Initializing a struct with the contents of a std::vector<unsigned char>
[英]Populate a struct from data in a std::vector<unsigned char>
我有以下結構定義從HID設備報告的集合返回的數據:
struct DevInfo {
char unknown[0x40];
string name;
char unknown2[0x240];
};
目前尚不完整,但這與我的問題無關。 以前,我使用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";
這行得通,除了我顯然在做我不應該做的事情(從函數返回對char數組的引用)。 因此,在研究之后,我切換到了更安全的std::vector<unsigned char>
方法,但是現在我無法使用memcpy
來填充結構中的數據。
有人建議我使用std::vector<DevInfo>
代替std::vector<unsigned char>
,但是問題是可以從HID設備中檢索到幾種不同的報告,因此我需要能夠使用相同的函數( sendCommand
)填充不同的結構。
從我的std::vector<unsigned char>
到我的DevInfo
結構中獲取二進制數據的合適方法是什么?
只要它是普通可復制的標准布局類型,就不會阻止您使用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()
但是,在您的情況下,您似乎有一個非平凡的數據成員(假設該string
引用了std::string
),因此您將無法執行上述任何一項操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.