📄 struct.so
字号:
m4_comment([$Id: struct.so,v 10.8 2002/12/22 20:42:09 bostic Exp $])m4_ref_title(Access Methods, Storing C/C++ structures/objects,, am_misc/partial, am_misc/perm)m4_p([dnlm4_db can store any kind of data, that is, it is entirely 8-bit clean.How you use this depends, to some extent, on the application languageyou are using. In the C/C++ languages, there are a couple of differentways to store structures and objects.])m4_p([dnlFirst, you can do some form of run-length encoding and copy yourstructure into another piece of memory before storing it:])m4_indent([dnlstruct { char *data1; u_int32_t data2; ...} info;size_t len;u_int8_t *p, data_buffer__LB__1024__RB__;m4_blankp = &data_buffer__LB__0__RB__;len = strlen(info.data1);memcpy(p, &len, sizeof(len));p += sizeof(len);memcpy(p, info.data1, len);p += len;memcpy(p, &info.data2, sizeof(info.data2));p += sizeof(info.data2);...])m4_p([dnland so on, until all the fields of the structure have been loaded intothe byte array. If you want more examples, see the m4_db loggingroutines (for example, btree/btree_auto.c:__bam_split_log()). Thistechnique is generally known as "marshalling". If you use thistechnique, you must then un-marshall the data when you read it back:])m4_indent([dnlstruct { char *data1; u_int32_t data2; ...} info;size_t len;u_int8_t *p;m4_blankp = &data_buffer__LB__0__RB__;memcpy(&len, p, sizeof(len));p += sizeof(len);info.data1 = malloc(len);memcpy(info.data1, p, len);p += len;memcpy(&info.data2, p, sizeof(info.data2));p += sizeof(info.data2);...])m4_p([dnland so on.])m4_p([dnlThe second way to solve this problem only works if you have just onevariable length field in the structure. In that case, you can declarethe structure as follows:])m4_indent([dnlstruct { int a, b, c; u_int8_t buf__LB__1__RB__;} info;])m4_p([dnlThen, let's say you have a string you want to store in this structure.When you allocate the structure, you allocate it as:])m4_indent([dnlmalloc(sizeof(struct info) + strlen(string));])m4_p([dnlSince the allocated memory is contiguous, you can the initialize thestructure as:])m4_indent([dnlinfo.a = 1;info.b = 2;info.c = 3;memcpy(&info.buf__LB__0__RB__, string, strlen(string) + 1);])m4_p([dnland give it to m4_db to store, with a length of:])m4_indent([dnlsizeof(struct info) + strlen(string);])m4_p([dnlIn this case, the structure can be copied out of the database and usedwithout any additional work.])m4_page_footer
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -