I want to store a JPEG image in redis as a single key-value pair.
From OpenCV, I get a std::vector<unsigned char> jpeg
from imencode()
Now I convert this vector to std::string
and SET
it with Hiredis.
The problem is that the jpeg
vector contains NUL
characters (ANSII == 0
) and the Hiredis SET
function receives value.c_str()
. .c_str()
truncates the string after the first occurrence of NUL
, and therefore only this substring is stored in the DB.
My question is: How can I SET
and GET
a std::vector<unsigned char>
(containing NUL
) with Hiredis? (Minimizing runtime is critical.)
Here is my code:
// 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;
}