C 结构序列化

C++ struct serialization

本文关键字:序列化 结构      更新时间:2023-10-16

我正在实现一个数据缓冲区,该数据缓冲区从一个应用程序中接收带有过程调用的音频数据软件包(无需在同一机器上运行的两个应用程序),然后将其放入一个结构中,并将其写入一个映射的文件。

因此,Writer应用程序可以调用我的应用程序的过程,该过程将像void writeData (DataItem data, Timestamp ts)一样smth,每秒大约15次,每个数据项大小2MB。

我的应用程序应将数据存储到

之类的结构中
Struct DataItem 
{
long id;
...  Data; 
Time  insertTime;
}

并将其写入文件以将来阅读目的。

因此,由于很难将结构保存到文件中,因此我认为(?)需要将其写为二进制文件。因此,我不确定我是否需要使用任何类型的序列化(例如boost serialization)?

我不知道如何将此数据对齐以获取内存映射文件,以及如何从文件中重新构造数据。

我搜索互联网,但找不到太多代码示例。和示例代码将被贴上杂项。

顺便说一下,我使用Windows 7 X64嵌入式和Visual Studio 2008。

谢谢...

序列化的常见C 方法是:

struct myStruct
{
    int         IntData;
    float       FloatData;
    std::string StringData;
};
std::ostream& operator<<(std::ostream &os, const myStruct &myThing)
{
    os
    << myThing.IntData      << " "
    << myThing.FloatData    << " "
    << myThing.StringData   << " "
    ;
    return os;
}
std::istream& operator>>(std::istream &is, myStruct &myThing)
{
    is 
    >> myThing.IntData
    >> myThing.FloatData
    >> myThing.StringData;
    return is;
}

void WriteThing()
{
    myStruct myThing;
    myThing.IntData = 42;
    myThing.FloatData = 0.123;
    myThing.StringData = "My_String_Test";
    std::ofstream outFile;
    outFile.open("myFile.txt");
    outFile << myThing;
}
void ReadThing()
{
    myStruct myThing;
    std::ifstream inFile;
    inFile.open("myFile.txt");    
    inFile >> myThing;
}

请注意:

  • std :: String定义运营商&lt;&lt;>>。这些会在上面的代码。
  • 流将将白空间字符视为定界符。用空白存储字符串将需要额外的处理
  • 如果您打算通过更新来保留数据软件,您必须实现某种文件版本
  • 请参阅Fstream的文档,以了解如何移动文件指针在一个大文件上使用seek等。

使用boost ::序列化与文本存档。
是解决平台独立性的最"标准"方式。
可选,您可以在其顶部设置GZIP压缩。

您确定要问C 而不是C#吗?您的代码示例看起来像C#

在C 中,如果您的struct格式不会更改,则可以将数组写入磁盘。

这是您要求的示例,但这实际上是C 101东西

FILE* output=fopen ("myfile", "wb");
fwrite (array, sizeof (mystruct), number_of_elements_in_array, output);
fclose (output);