0

在 redis 中存储 POD 结构可以正常工作,const char *但不std::string涉及。

常量字符 * 示例

#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: %s\n", context->errstr);
      } else {
          printf("Can't allocate redis context\n");
      }
      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);

执行总是以Segmentation fault结束。

我自己无法解决这个问题,我非常感谢任何帮助。

4

1 回答 1

-1

好的,我明白了:替换第二条redisCommand语句

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

解决了这个问题。

于 2016-12-27T18:11:19.390 回答