简体   繁体   English

将数据结构c ++保存到磁盘

[英]saving data structure c++ to disk

I have a very complex data structure with pointers to various parts of the memory. 我有一个非常复杂的数据结构,指向内存的各个部分。 It takes a while to build and I would like to save the "memory" used by that structure to the disk. 构建需要一段时间,我想将该结构使用的“内存”保存到磁盘。 Then, when the program is launched again, it would just memory map the file and I could use it. 然后,当程序再次启动时,它将只是内存映射文件,我可以使用它。 Is there any way to do this ? 有没有办法做到这一点?

boost::serialization could do it. boost :: serialization可以做到。 Note: write the archive version first and then do register_types 注意:首先编写存档版本,然后执行register_types

It can be done, yes, but you need to be aware of how the structure is actually stored in memory, and how that changes on various platforms (alignment, packing, byte-ordering, primitive type sizes, etc.). 可以这样做,是的,但你需要知道结构实际存储在内存中的方式,以及它在各种平台上的变化(对齐,打包,字节排序,基本类型大小等)。 Additionally, it would be prudent to change your "pointers to various parts" into "offsets to various parts" since actual memory locations will change between process uses. 此外,将“指向各个部分的指针”更改为“各部分的偏移”是谨慎的,因为实际的内存位置将在进程使用之间发生变化。

example, writing an object like this to disk should be fairly portable: 例如,将这样的对象写入磁盘应该是相当可移植的:

#pragma pack(1)
typedef struct {
   unsigned char data8[8];
   unsigned char data4[4];
   unsigned char offset[2];
   unsigned char data2[2];
} MyStruct;
#pragma pack() // to return to default

but one like this would be very problematic: 但是像这样的人会有很多问题:

typedef struct _MyStruct {
   unsigned long long data8;
   unsigned int data4;
   struct _MyStruct *nextOne;
   unsigned short data2;
} MyStruct;

You could start with Boost.Interprocess and use memory maped files. 您可以从Boost.Interprocess开始并使用内存maped文件。 Your data structure will look a litle differnt (pointers are smart pointers, references forbidden, no virtual functions). 您的数据结构将看起来不同(指针是智能指针,引用被禁止,没有虚函数)。 But it should be manageable. 但它应该是可管理的。 At least all types you use needs to be constructable in shared memory. 至少您使用的所有类型都需要在共享内存中构建。 Some are (Boost.Container) and some are not (Boost.Any, Boost.Variant). 有些是(Boost.Container),有些则不是(Boost.Any,Boost.Variant)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM