2014-11-07 2 views
2

주어진 경우 : int x [3] = {11,22,33}; 어떻게hiredis가 Redis에서 키의 값으로 C int 배열을 설정할 수 있습니까?

hiredis 이진 safestring에게

/* Set a key using binary safe API */ 
    reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5); 
    printf("SET (binary API): %s\n", reply->str); 
    freeReplyObject(reply); 

을 설정하는 방법에 대한 예제를 제공하지만 어떻게 다른 데이터를 어떻게 얻는 방법에 대해 이진 데이터와 같은 키의 값으로 저장하고받을 수 있나요?

답변

2

마샬링을 사용하지 않고 원격 저장소에 직접 바이너리 데이터를 저장하면 재앙이 발생합니다. 바이너리 데이터를 플랫폼과 독립적으로 만들 수있는 일련의 프로토콜이 많이 있습니다. 당신이 당신의 레디 스의 클라이언트가 동일한 엔디 언과 같은를 sizeof (int)를 가진 시스템에서 실행해야하는 경우 이런 종류의 코드는 작동

// This is the key 
int k[3] = {11,22,33}; 

// This is the value 
int v[4] = {0,1,2,3}; 
redisReply *reply = 0; 

// Store the key/value: note the usage of sizeof to get the size of the arrays (in bytes) 
reply = redisCommand(context, "SET %b %b", k, (size_t) sizeof(k), v, (size_t) sizeof(v)); 
if (!reply) 
    return REDIS_ERR; 
freeReplyObject(reply); 

// Now, get the value back, corresponding to the same key 
reply = redisCommand(context, "GET %b", k, (size_t) sizeof(k)); 
if (!reply) 
    return REDIS_ERR; 
if (reply->type != REDIS_REPLY_STRING) { 
    printf("ERROR: %s", reply->str); 
} else { 

    // Here, it is safer to make a copy to be sure memory is properly aligned 
    int *val = (int *) malloc(reply->len); 
    memcpy(val, reply->str, reply->len); 
    for (int i=0; i<reply->len/sizeof(int); ++i) 
     printf("%d\n",val[i]); 
    free(val); 
} 
freeReplyObject(reply); 

참고 : 말했다

는 귀하의 질문에 대답합니다.

+0

답장을 보내 주셔서 감사 드리며, 필요한 것입니다. 제 영어는 아주 좋지 않습니다. 감사합니다. –