在前面的文章中阐述了key value数据库写入记录等。但是在处理C结构体的时候,通常需要特殊处理一下。
对于数据的写入通常为memcpy的方式,将一段内存的信息直接进行写入。我们以Berkeley DB为例:
http://download.oracle.com/docs/cd/E17076_02/html/gsg/C/cstructs.html
1.结构体中没有含指针
#include <db.h> #include <string.h> typedef struct my_struct { int id; char familiar_name[MAXLINE]; /* Some suitably large value */ char surname[MAXLINE]; } MY_STRUCT; ... DBT key, data; DB *my_database; MY_STRUCT user; char *fname = "David"; char *sname = "Rider"; /* Database open omitted for clarity */ user.id = 1; strncpy(user.familiar_name, fname, strlen(fname)+1); strncpy(user.surname, sname, strlen(sname)+1); /* Zero out the DBTs before using them. */ memset(&key, 0, sizeof(DBT)); memset(&data, 0, sizeof(DBT)); key.data = &(user.id); key.size = sizeof(int); data.data = &user; data.size = sizeof(MY_STRUCT); my_database->put(my_database, NULL, &key, &data, DB_NOOVERWRITE);
可以直接按照字符串的方式写入。
2.含有指针的结构体
将指针指向的分配内存,都统一进行malloc分配。组成统一的一段内存信息。
#include <db.h> #include <string.h> #include <stdlib.h> typedef struct my_struct { int id; char *familiar_name; char *surname; } MY_STRUCT; ... DBT key, data; DB *my_database; MY_STRUCT user; int buffsize, bufflen; char fname[ ] = "Pete"; char sname[10]; char *databuff; strncpy(sname, "Oar", strlen("Oar")+1); /* Database open omitted for clarity */ user.id = 1; user.familiar_name = fname; user.surname = sname; /* Some of the structure's data is on the stack, and * some is on the heap. To store this structure's data, we * need to marshall it -- pack it all into a single location * in memory. */ /* Get the buffer */ buffsize = sizeof(int) + (strlen(user.familiar_name) + strlen(user.surname) + 2); databuff = malloc(buffsize); memset(databuff, 0, buffsize); /* copy everything to the buffer */ memcpy(databuff, &(user.id), sizeof(int)); bufflen = sizeof(int); memcpy(databuff + bufflen, user.familiar_name, strlen(user.familiar_name) + 1); bufflen += strlen(user.familiar_name) + 1; memcpy(databuff + bufflen, user.surname, strlen(user.surname) + 1); bufflen += strlen(user.surname) + 1; /* Now store it */ /* Zero out the DBTs before using them. */ memset(&key, 0, sizeof(DBT)); memset(&data, 0, sizeof(DBT)); key.data = &(user.id); key.size = sizeof(int); data.data = databuff; data.size = bufflen; my_database->put(my_database, NULL, &key, &data, DB_NOOVERWRITE); free(sname); free(databuff);
3.总结
对于key value数据库中,如果写入的结构体过于复杂,处理并不方便,但是不用指针,基本不可能。
还需要对于这方面进行一个研究。