Click here to Skip to main content
15,880,725 members
Articles / Desktop Programming / MFC

A Serialization Primer - Part 1

Rate me:
Please Sign up or sign in to vote.
4.64/5 (43 votes)
25 Nov 2002CPOL2 min read 371.8K   185   66
This tutorial describes how to easily serialize a simple object.

This article is the first of a 3 part tutorial on serialization.

  • Part 1 introduces the basics of serialization.
  • Part 2 explains how to gracefully handle reading invalid data stores and support versioning.
  • Part 3 describes how to serialize complex objects.

Serialization is the process of writing or reading an object to or from a persistent storage medium, such as a disk file. Serializing an object requires 3 ingredients:

  • A CFile object representing the datafile
  • A CArchive object that provides the serialization context
  • The object being serialized

Serialization data flow

Step 1 - Open the datafile

To serialize an object to the file "foo.dat", open the file with the appropriate access mode. In this example, the file is opened for exclusive read/write access.

C++
// Open file "foo.dat"
CFile* pFile = new CFile();
ASSERT (pFile != NULL);
if (!pFile->Open ("foo.dat", CFile::modeReadWrite | CFile::shareExclusive)) {
    // Handle error
    return;
}

Step 2 - Hook Up the Archive

Next, a CArchive object is hooked up to the file. The archive provides an efficient conduit to persistent storage. Instead of directly reading and writing the file, you serialize data to and from the archive. The archive needs to know if you're going to be using it to read or write data. In this example, we'll assume we're writing data.

C++
// Create archive ...
bool bReading = false;  // ... for writing
CArchive* pArchive = NULL;
try
{
  pFile->SeekToBegin();
  UINT uMode = (bReading ? CArchive::load : CArchive::store);
  pArchive = new CArchive (pFile, uMode);
  ASSERT (pArchive != NULL);
}
catch (CException* pException)
{
  // Handle error
  return;
}

Step 3 - Serialize the Object

Finally, we serialize the object by calling its serialize() method. serialize() is just a method we made up. It has nothing to with MFC's CObject::Serialize(). Also, you don't have to derive your object from CObject. Our serialize() method takes a pointer to a CArchive and returns an integer status.

C++
int CFoo::serialize
  (CArchive* pArchive)
{
  int nStatus = SUCCESS;

  // Serialize the object ...
  ...

  return (nStatus);
}

We'll get to the actual serialization process in a minute. Meanwhile, let's recognize a couple of important points:

  • The same method CFoo::serialize() is used to read/write the object from/to persistent storage.
  • CFoo::serialize() doesn't know anything about the datafile bring accessed.

Assume CFoo represents an employee record that contains a couple of data members.

C++
class CFoo
{
  // Construction/destruction
  public:
    CFoo::CFoo();
    virtual CFoo::~CFoo();

  // Methods
  public:
    int serialize (CArchive* pArchive);

  // Data members
  public:
    CString  m_strName;  // employee name
    int      m_nId;      // employee id
};

We use CArchive's streaming operators << and >> to read/write the data members from/to the archive. CArchive knows how to serialize simple data types like int, float, DWORD, and objects like CString. The archive also knows whether it's in read or write mode. You can query its mode by calling CArchive::IsStoring(). CFoo's serialization method can then be written as:

C++
int CFoo::serialize
  (CArchive* pArchive)
{
  int nStatus = SUCCESS;

  // Serialize the object ...
  ASSERT (pArchive != NULL);
  try
  {
    if (pArchive->IsStoring()) {
       // Write employee name and id
       (*pArchive) << m_strName;
       (*pArchive) << m_nId;
    }
    else {
       // Read employee name and id
       (*pArchive) >> m_strName;
       (*pArchive) >> m_nId;
    }
  }
  catch (CException* pException)
  {
    nStatus = ERROR;
  }
  return (nStatus);
}

Step 4 - Clean Up

When you've finished serializing, you should clean up by closing the archive and datafile.

C++
pArchive->Close();
delete pArchive;
pFile->Close();
delete pFile();

Conclusion

Well, there you have it - serialization in a (very small) nutshell. In Part 2, we'll see how to gracefully handle reading invalid data stores and support different versions of our object. In Part 3, we'll see how to serialize complex objects.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Canada Canada
Ravi Bhavnani is an ardent fan of Microsoft technologies who loves building Windows apps, especially PIMs, system utilities, and things that go bump on the Internet. During his career, Ravi has developed expert systems, desktop imaging apps, marketing automation software, EDA tools, a platform to help people find, analyze and understand information, trading software for institutional investors and advanced data visualization solutions. He currently works for a company that provides enterprise workforce management solutions to large clients.

His interests include the .NET framework, reasoning systems, financial analysis and algorithmic trading, NLP, HCI and UI design. Ravi holds a BS in Physics and Math and an MS in Computer Science and was a Microsoft MVP (C++ and C# in 2006 and 2007). He is also the co-inventor of 3 patents on software security and generating data visualization dashboards. His claim to fame is that he crafted CodeProject's "joke" forum post icon.

Ravi's biggest fear is that one day he might actually get a life, although the chances of that happening seem extremely remote.

Comments and Discussions

 
GeneralRe: CObject Pin
Ravi Bhavnani5-Dec-02 1:16
professionalRavi Bhavnani5-Dec-02 1:16 
GeneralRe: CObject Pin
Zac Howland3-Feb-03 6:24
Zac Howland3-Feb-03 6:24 
QuestionSmall bug? Pin
Anonymous13-Nov-02 8:24
Anonymous13-Nov-02 8:24 
AnswerRe: Small bug? Pin
Ravi Bhavnani13-Nov-02 8:36
professionalRavi Bhavnani13-Nov-02 8:36 
GeneralRe: Small bug? Pin
Brian Delahunty26-Nov-02 7:53
Brian Delahunty26-Nov-02 7:53 
Generalcode Pin
newbie200219-Aug-02 23:59
newbie200219-Aug-02 23:59 
GeneralRe: code Pin
Ravi Bhavnani20-Aug-02 4:27
professionalRavi Bhavnani20-Aug-02 4:27 
Yes, I'll post a sample project soon.

/ravi

Let's put "civil" back in "civilization"
http://www.ravib.com
ravib@ravib.com
GeneralSlight Bug Pin
5-Jun-02 18:42
suss5-Jun-02 18:42 
GeneralRe: Slight Bug Pin
Ravi Bhavnani7-Jun-02 12:16
professionalRavi Bhavnani7-Jun-02 12:16 
GeneralProper examples would be nice Pin
13-May-02 23:23
suss13-May-02 23:23 
GeneralThe beast simplified Pin
Matt Newman19-Feb-02 16:23
Matt Newman19-Feb-02 16:23 
GeneralRe: The beast simplified Pin
Zac Howland3-Feb-03 6:38
Zac Howland3-Feb-03 6:38 
GeneralNice Article Pin
akraus18-Feb-02 21:28
akraus18-Feb-02 21:28 
GeneralRe: Nice Article Pin
Ravi Bhavnani19-Feb-02 1:37
professionalRavi Bhavnani19-Feb-02 1:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.