在redis中存储POD结构与DECLARE @id TABLE (id int, childId int);
INSERT INTO @id SELECT 1, 2;
INSERT INTO @id SELECT 2, 4;
INSERT INTO @id SELECT 3, 5;
INSERT INTO @id SELECT 4, 6;
INSERT INTO @id SELECT 5, null;
INSERT INTO @id SELECT 6, null;
WITH cte AS
(
SELECT id, childId, id AS anchorId
FROM @id
WHERE id IN (1,3)
UNION ALL
SELECT b.id, b.childId, cte.anchorId
FROM @id b
INNER JOIN cte
ON b.id = cte.childId
)
SELECT
id
, childId
, CASE
WHEN id = anchorId THEN NULL
ELSE anchorId
END AS anchorId
FROM cte
一起正常工作,但如果涉及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);
执行始终以分段错误结束。
我不能自己解决这个问题,我真的很感激任何帮助。
答案 0 :(得分:-1)
好的,我明白了:
替换第二个redisCommand
语句
reply = (redisReply *) redisCommand(context, "GET %b", key.c_str(), key.size());
解决了这个问题。