[英]Dynamic (type) binary buffer in C++?
Currently, I'm using std::vector<char>
like this: 当前,我正在使用
std::vector<char>
像这样:
char data, data2, data3;
vec.push_back(data);
vec.push_back(data2);
vec.push_back(data3);
However, since I'm storing binary data, sometimes I need to push data of different sizes (ie not a single char), and I need to manually split that data into single bytes, which is not convenient or readable. 但是,由于我存储的是二进制数据,有时我需要推送不同大小的数据(即不是单个char),并且需要手动将该数据拆分为单个字节,这不方便也不易读。
Something like this would be perfect: 这样的事情将是完美的:
buffer.push<int>(some_int); // some_int = 0xAABBCCDD
buffer.push<char>(some_char); // some_char = 0xFF
buffer.push("arbitrary_data", arbitrary_length);
The resulting memory would be: 结果内存为:
AA BB CC DD FF ...........
// ^ int
// ^ char
Is there any standard way of doing it, or I need libraries / own implementation? 有什么标准的方法吗,还是我需要库/自己的实现?
What you're looking for is called serialization, and it's not part of the ISO standard. 您正在寻找的被称为序列化,它不是ISO标准的一部分。 Boost does have a library for it, though.
不过,Boost确实有一个库。
You could use pointer arithmetic in combine with reinterpret_cast
like the example bellow: 您可以将指针算术与
reinterpret_cast
结合使用,例如下面的示例:
std::vector<char> v;
v.push_back('a');
v.push_back('b');
int a = 20;
v.insert(v.end(), reinterpret_cast<char*>(&a), reinterpret_cast<char*>(&a) + sizeof(a));
or if you have a class/struct: 或者如果您有一个类/结构:
struct foo {int a = 1 , b = 2, c = 3;};
std::vector<char> v;
foo b;
v.insert(v.end(), reinterpret_cast<char*>(&b), reinterpret_cast<char*>(&b) + sizeof(b));
What about this? 那这个呢? It works even for non-POD types!
它甚至适用于非POD类型! (Note: C++11 code!)
(注意:C ++ 11代码!)
#include <new>
#include <vector>
#include <utility>
class BinaryVector : public std::vector<unsigned char> {
public:
template<typename T>
void push(const T &what) {
this->resize(this->size() + sizeof(T));
new(this->data() + this->size() - sizeof(T)) T(what);
}
template<typename T>
void push(T &&what) {
this->resize(this->size() + sizeof(T));
new((T*)(this->data() + this->size() - sizeof(T))) T(XValue(what));
}
template<typename T>
T pop() {
T tmp(std::move(*(T*)(this->data() + this->size() - sizeof(T))));
((T*)(this->data() + this->size() - sizeof(T)))->~T();
this->resize(this->size - sizeof(T));
return tmp;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.