C++,弹性云服务器和保存/加载

C++, ECS and Saving / Loading

本文关键字:保存 加载 服务器 C++      更新时间:2023-10-16

我有一个使用实体-组件-系统框架的程序。从本质上讲,这意味着我有一个实体集合,这些实体附加了各种组件。实体实际上只是整数 ID 号,通过将组件映射到实体的指定 ID 号来附加到实体的组件。

现在,我需要

将实体和关联组件的集合存储到一个可以在以后修改的文件中,所以基本上我需要保存和加载功能。然而,作为一个C++新手,我很难弄清楚如何做到这一点。

来自 Java 和 C#,我的第一选择是将对象序列化为 JSON,然后在加载 JSON 时反序列化它们。但是,C++没有任何反射功能。所以,问题是:如何保存和加载C++对象?我的意思不是实际的文件操作,我的意思是处理对象和结构的方式,以便在程序启动之间保留它们。

一种方法是在C++中创建持久对象,并存储数据。

查看以下链接:

C++类似于永恒的对象持久性库

http://sourceforge.net/projects/litesql/

http://en.wikipedia.org/wiki/ODB_(C%2B%2B)

http://drdobbs.com/cpp/184408893

http://tools.devshed.com/c/a/Web-Development/C-Programming-Persistence/

C++ 不直接支持持久性(有人建议将来将持久性和反射添加到C++中)。持久性支持并不像最初看起来那么微不足道。同一对象的大小和内存布局可能因平台而异。不同的字节顺序或字节序使事情进一步复杂化。为了使对象持久化,我们必须将其状态保留在非易失性存储设备中。ie:编写一个持久对象,以将其状态保留在创建它的程序范围之外。

另一种方法是将对象存储到数组中,然后将数组缓冲区推送到文件中。优点是磁盘盘片不会浪费时间,并且可以连续执行写入。

可以使用线程来提高性能。将对象转储到缓冲区,完成后触发线程处理输出。

例:以下代码尚未编译,仅用于说明目的。

#include <fstream>
#include <algorithm>
using std::ofstream;
using std::fill;
#define MAX_DATA_LEN  1024 // Assuming max size of data be 1024
class stream_interface
{
    virtual void    load_from_buffer(const unsigned char *& buf_ptr) = 0;
    virtual size_t  size_on_stream(void) const = 0;
    virtual void    store_to_buffer(unsigned char *& buf_ptr) const = 0;
};
struct Component 
    : public stream_interface,
    data_length(MAX_DATA_LEN)
{
    unsigned int entity;
    std::string  data;
    const unsigned int  data_length;
    void load_from_buffer(const unsigned char *& buf_ptr)
    {
        entity = *((unsigned int *) buf_ptr);
        buf_ptr += sizeof(unsigned int);
        data = std::string((char *) buf_ptr);
        buf_ptr += data_length;
        return;
    }
    size_t size_on_stream(void) const
    {
        return sizeof(unsigned int) + data_length;
    }
    void store_to_buffer(unsigned char *& buf_ptr) const
    {
        *((unsigned int *) buf_ptr) = entity;
        buf_ptr += sizeof(unsigned int);
        std::fill(buf_ptr, 0, data_length);
        strncpy((char *) buf_ptr, data.c_str(), data_length);
        buf_ptr += data_length;
        return;
    }
};

int main(void)
{
    Component c1;
    c1.data = "Some Data";
    c1.entity = 5;
    ofstream    data_file("ComponentList.bin", std::ios::binary);
    // Determine size of buffer
    size_t  buffer_size = c1.size_on_stream();
    // Allocate the buffer
    unsigned char * buffer = new unsigned char [buffer_size];
    unsigned char * buf_ptr = buffer;
    // Write / store the object into the buffer.
    c1.store_to_buffer(buf_ptr);
    // Write the buffer to the file / stream.
    data_file.write((char *) buffer, buffer_size);
    data_file.close();
    delete [] buffer;
    return 0;
}