如果将键定义为std :: string,则存储在REDIS中的POD结构的验证将失败

deserialization of pod struct stored in redis fails if key is defined as std::string

本文关键字:POD REDIS 中的 失败 验证 结构 定义 std string 如果 存储      更新时间:2023-10-16

pod struct在redis中的存储与 const char *一起工作,但如果涉及 std::string,则不行。

const char *示例

#include <hiredis/hiredis.h>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
struct Test
{
  const uint32_t id;
  const char *name;
};
int main() {
  redisContext *context = redisConnect("127.0.0.1", 6379);
  if (context == NULL || context->err) {
      if (context) {
          printf("Error: %sn", context->errstr);
      } else {
          printf("Can't allocate redis contextn");
      }
      exit(EXIT_FAILURE);
  }
  Test obj = {(uint32_t) 123, "foo bar"};
  const size_t size = 2 * sizeof(uint32_t) + (strlen(obj.name) + 1);
  cout << "object{id: " << obj.id << ", name:' " << obj.name << "'}; size: " << size << endl;
  redisReply *reply = 0;
  const char *key = strdup("some-key");
  reply = (redisReply *) redisCommand(context, "SET %b %b", key, strlen(key), &obj, size);
  if (!reply)
      return REDIS_ERR;
  freeReplyObject(reply);
  reply = (redisReply *) redisCommand(context, "GET %s", key);
  if (!reply)
      return REDIS_ERR;
  Test *res = (struct Test*) reply->str;
  cout << "result{id: " << res->id << ", name:' " << res->name << "'}; size: " << size << endl;
  freeReplyObject(reply);
  redisFree(context);
}

如果我更换行:

  const char *key = strdup("some-key");
  reply = (redisReply *) redisCommand(context, "SET %b %b", key, strlen(key), &obj, size);

std::string key("some-key");
reply = (redisReply *) redisCommand(context, "SET %b %b", key.c_str(), key.size(), &obj, size);

执行始终以分段故障结束。

我无法自己解决这个问题,我真的很感谢任何帮助。

好吧,我明白了:更换第二个redisCommand语句

reply = (redisReply *) redisCommand(context, "GET %b", key.c_str(), key.size());

解决了问题。