既然你要處理非POD數據,您需要將結構數據壓扁成一個序列化格式,其他應用程序可以再在其結尾解析回結構。
你的ListOfItems
矢量可以非常容易扁平,因爲它的元素是POD數據。存儲vector
大小的整數,複製到緩衝區,然後複製每個Item
事後(假設緩衝器是足夠大以保持扁平的數據):
long double* Data = static_cast<long double*>(pData);
//Check if Data[1] contains a request command then copy.
unsigned char *Work = static_cast<unsigned char *>(pData);
int number = ListOfItems.size();
CopyMemory(Work, &number, sizeof(int));
Work += sizeof(int);
for (int i = 0; i < number; ++i)
{
CopyMemory(Work, &ListOfItems[i], sizeof(Item));
Work += sizeof(Item);
}
你ListOfModels
矢量將是有點困難變平因爲Model
包含另一個vector
中,但相同的概念適用於一般:
long double* Data = static_cast<long double*>(pData);
//Check if Data[1] contains a request command then copy.
unsigned char *Work = static_cast<unsigned char *>(pData);
int number = ListOfModels.size();
CopyMemory(Work, &number, sizeof(int));
Work += sizeof(int);
for (int i = 0; i < number; ++i)
{
Model &m = ListOfModels[i];
CopyMemory(Work, &(m.SX), sizeof(int) * 5);
Work += (sizeof(int) * 5);
int num = m.Vertices.size();
CopyMemory(Work, &num, sizeof(int));
Work += sizeof(int);
for (int j = 0; j < num; ++j)
{
Vector3D &v = m.Vertices[j];
// copy v as needed...
Work += ...;
}
// copy m.VBOPointer as needed ...
Work += ...;
}
我通常這樣的事情做的是使用模板來幫助簡化邏輯,使其更易於閱讀:
template<typename T>
void Copy(unsignd char* &Work, const T &value)
{
CopyMemory(Work, &value, sizeof(T));
}
template<template T>
void Copy(unsigned char* &Work, const std::vector<T> &vec)
{
int number = vec.size();
Copy(Work, number);
for (int i = 0; i < number; ++i)
Copy(Work, vec[i]);
}
。
long double* Data = static_cast<long double*>(pData);
//Check if Data[1] contains a request command then copy.
unsigned char *Work = static_cast<unsigned char *>(pData);
Copy(Work, ListOfItems);
。
template<>
void Copy<Vector3D>(unsigned char* &Work, const Vector3D &vec)
{
// copy vec as needed...
Work += ...;
}
template<>
void Copy<Model>(unsigned char* &Work, const Model &m)
{
Copy(Work, m.SX);
Copy(Work, m.SY);
Copy(Work, m.X);
Copy(Work, m.Y);
Copy(Work, m.Z);
Copy(Work, m.Vertices);
// copy m.VBOPointer as needed ...
Work += ...;
}
long double* Data = static_cast<long double*>(pData);
//Check if Data[1] contains a request command then copy.
unsigned char *Work = static_cast<unsigned char *>(pData);
Copy(Work, ListOfModels);
我會寫一個序列化和反序列化功能,爲每個類 – Gir 2012-08-10 21:10:21
使用第三方 - 谷歌的protobuf想到的。 – 2012-08-10 21:11:25
XDR是完全獨立於相關機器的標準方式。你可以像@Gir所說的那樣在你的'Serialize'和'Deserialize'函數中使用它。 – Hbcdev 2012-08-10 21:15:45