在redis中存储chars的向量 - 包含nul
Storing vector of chars in Redis - containing NUL
我想将JPEG图像存储在Redis中,作为单个键值对。从OpenCV,我从imencode()
std::vector<unsigned char> jpeg
现在,我将此向量转换为std::string
,并用Hiredis将其转换为SET
。问题在于jpeg
向量包含NUL
字符(ANSII == 0
),而Hiredis SET
功能接收value.c_str()
。.c_str()
在第一次出现NUL
之后将字符串截断,因此仅将此子字符串存储在DB中。
我的问题是:如何使用HIREDIS SET
和GET
A std::vector<unsigned char>
(包含NUL
)?(最小化运行时至关重要。)
这是我的代码:
// Create vector of uchars, = From CV [Disregard inefficiency here]
std::vector<unsigned char> jpeg;
jpeg.push_back( 'a' );
jpeg.push_back( 'b' );
jpeg.push_back( (unsigned char) 0 );
jpeg.push_back( 'c' );
jpeg.push_back( 'd' );
// Convert to string
std::string word = "";
for (int i=0; i<jpeg.size(); ++i)
{
word.push_back(jpeg[i]);
}
std::cout << "word = " << word << std::endl;
std::cout << "word.c_str() = " << word.c_str() << std::endl;
// connect redis
std::string hostname = "127.0.0.1";
int port = 6379;
timeval timeout = { 1, 500000 }; // 1.5 seconds
redisContext* context = redisConnectWithTimeout(hostname.c_str(), port, timeout);
// set redis
std::string key = "jpeg";
redisReply* reply = (redisReply *)redisCommand(context, "SET %s %s", key.c_str(), word.c_str() );
freeReplyObject( (void*) reply);
// get redis
reply = (redisReply *)redisCommand(context, "GET %s", key.c_str() );
std::string value = reply->str;
freeReplyObject((void*) reply);
std::cout << "returned value = " << value << std::endl;
// Convert back to vector of uchars (this should be the same as the original jpeg) [Disregard inefficiency here]
std::vector<unsigned char> jpeg_returned;
for (int i=0; i<value.size(); ++i)
{
jpeg_returned.push_back(value[i]);
// std::cout << "value[i] = " << value[i] << std::endl;
}
在显示代码之前,我想再次警告一次,即不正确序列化存储二进制数据可能是有问题的。至少要确保所有服务器都是相同的,并且具有相同的尺寸(int)。
std::vector<char> v{'A', 'B', ' ', 'C', 'D'};
std::string key = "jpeg";
redisReply* reply = static_cast<redisReply *>( redisCommand(context, "SET %s %b", key.c_str(), v.data(), v.size() ) );
freeReplyObject( reply );
和python的阅读。
>>> import redis
>>> r = redis.StrictRedis(host='localhost', port=6379, db=0)
>>> r.get("jpeg")
'ABx00CD'
相关文章:
- 在C++中,如何创建包含可变模板对象的异构向量?
- 包含指向其他结构的指针向量的结构
- 在 C++ 向量构造中包含迭代器
- 当映射包含字符串向量作为值时,从值中获取键的有效方法
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 如何删除包含其他向量的向量?
- boost::interprocess::managed_mapped_file 如何包含弹性向量?
- 如果字符串向量包含字符'p',如何检查 c++
- C++11 向量包含 2 个不同的子类,但不能同时进行
- 如何将智能指针向量转换为常量向量,该常量向量包含指向常量的智能指针
- 在redis中存储chars的向量 - 包含nul
- 如何创建一个接受向量的类,该向量包含任何类型的数据
- 如果向量包含重复项,则此函数应返回 true。知道为什么它不起作用吗?
- 访问作为指向该类的指针向量包含的类的方法
- 在Vector中,一个向量包含8000个成员
- 如果向量a包含与向量b相同的元素,我如何有效地检查
- 类的向量包含函数
- 填充到一个向量中,该向量包含指向列表的指针
- 向量包含结构的排序