Introduction
People frequently ask how to serialize CArray
object. There is a simple way to serialize CArray
. You will find it very simple by reading an example.
Using the Example
This is the class for data to be serialized. I have used int
, CString
and char*
so you can understand better.
#pragma once
class SaveFile :public CObject
{
DECLARE_SERIAL(SaveFile)
public:
SaveFile(void);
SaveFile(SaveFile &Sv)
{*this=Sv;}
~SaveFile(void);
CString FName;
char *FData;
ULONGLONG MySize;
virtual void Serialize(CArchive &pArchive);
SaveFile& operator=(SaveFile & SvFi);
};
This is the CPP file of SaveFile
class. Use CArchive
to store and load CArray
from/to file.
#include "StdAfx.h"
#include "SaveFile.h"
IMPLEMENT_SERIAL(SaveFile,CObject,0)
SaveFile::SaveFile(void)
{}
SaveFile::~SaveFile(void)
{}
void SaveFile::Serialize(CArchive & pArchive)
{
CObject::Serialize(pArchive);
if(pArchive.IsStoring())
{
pArchive<<FName<<MySize;
for(int i=0;i<MySize;i++)
pArchive<<FData[i];
}
else
{ pArchive>>FName>>MySize;
FData=new char[MySize];
for(int i=0;i<MySize;i++)
pArchive>>FData[i];
}
}
SaveFile& SaveFile::operator =(SaveFile&SvFo)
{
FName=SvFo.FName;
MySize=SvFo.MySize;
FData=new char[MySize];
for(int i=0;i<MySize;i++)
FData[i]=SvFo.FData[i];
return *this;
}
SaveFileHandler
class is for storing/loading object of Savefile
class to/from file .
In this CPP of SaveFileHandler SerializeElements<SaveFile>(CArchive& ar, SaveFile* pElements, int nCount)
function is important. This is a global function which can be called from any class.
SaveFileHandler.h
#pragma once
#include "SaveFile.h"
class SaveFileHandler
{
public:
SaveFileHandler(void);
public:
~SaveFileHandler(void);
void AddSomeData();
void SerializeCArray();
CArray<SaveFile, SaveFile&> SF;
};
SaveFileHandler.cpp
#include "StdAfx.h"
#include "SaveFileHandler.h"
#include "SaveFile.h"
SaveFileHandler::SaveFileHandler(void)
{}
SaveFileHandler::~SaveFileHandler(void)
{}
SaveFileHandler::AddSomeData()
{
SaveFile SvFo ;
int Length; SvFo.FData=new char[(size_t)Length];
SvFo.MySize=Length;
for(int i=0;i<Length;i++)
SvFo.FData[i]=FData[i]; SvFo.FName=MainPath;
this->SF.Add(SvFo);
}
SaveFileHandler::SerializeCArray()
{
CFile SvFi("SomeFile.dhari",CFile::modeCreate|CFile::modeWrite);
CArchive Ar(&SvFi,CArchive::store);
this->SF.Serialize(Ar);
}
template <> inline void AFXAPI SerializeElements<SaveFile>
(CArchive& ar, SaveFile* pElements, int nCount)
{
for (int i=0;i < nCount; i++,pElements++)
{
if(ar.IsStoring())
{
pElements->Serialize(ar);
}
else
{
SaveFile* pSv = new SaveFile();
pSv->Serialize(ar);
*pElements = *pSv;
}
}
}
Conclusion
Feedback is welcome and appreciated whether it is constructive or not.
History
- 6th February, 2007: Initial post