void *Redis_create(char *host, int port) { redisContext *con; con = redisConnect(host, port); if (con == NULL || con->err) { if (con) { printf("Connection error: %s\n", con->errstr); redisFree(con); } else { printf("Connection error: can't allocate redis context\n"); } exit(1); } Redis proto = { .host = host, .port = port, .con = con, .init = Redis_init, .readReply = Redis_readReply, .close = Redis_close, .command = Redis_command }; Redis *m = calloc(1, sizeof(Redis)); *m = proto; if (!m->init(m)) { // looks like it didn't initialize properly m->close(m); return NULL; } else { // all done, we made an object of any type return m; } }
int main(int argc, char **argv) { char *hostname = (argc > 1) ? argv[1] : "127.0.0.1"; int port = (argc > 2) ? atoi(argv[2]) : 6379; Redis *r = Redis_create(hostname, port); r->command(r,"GET foo"); r->readReply(r); r->close(r); return 0; }