我的结构和向量看起来像:
typedef struct
{
int SX, SY;
int X, Y, Z;
std::vector<Vector3D> Vertices;
const void* VBOPointer;
} Model;
typedef struct
{
int X, Y;
struct
{
int VX[4], VY[4];
int TX[4], VY[4];
} Quad;
} Item;
std::vector<Item> ListOfItems;
std::vector<Model> ListOfModels;
我需要将这些复制到内存中,以便我可以从其他程序重建它们。我已经映射了内存,但后来我意识到我不能在其中任何一个上使用CopyMemory或MemCpy。
我该如何复制?
我如何复制标准数据类型/结构的示例:
struct
{
int X;
int Y;
} POD;
//pData is a void pointer to mapped memory given to be by MapFileView..
POD Foo = {100, 50};
long double* Data = static_cast<long double*>(pData);
//Check if Data[1] contains a request command then copy.
CopyMemory(&Data[0], &Foo, sizeof(Foo));
答案 0 :(得分:2)
由于您必须处理非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);