Click here to Skip to main content
15,880,543 members
Articles / Programming Languages / C++
Article

The Right Way To Do Object Serialization

Rate me:
Please Sign up or sign in to vote.
4.50/5 (7 votes)
15 May 2001CPOL3 min read 81.8K   34   9
A tip for using object serialization

Introduction

Object serialization is one of the most powerful features of MFC. With it you can store your objects into a file and let MFC recreate your objects from that file. Unfortunately there are some pitfalls in using it correctly. So it happened that yesterday I spent a lot of time in understanding what I did wrong while programming a routine that wrapped up some objects for a drag and drop operation. After a long debugging session I understood what happened and so I think that it might be a good idea to share my newly acquired knowledge with you.

The Wrong Way

Let's start with my wrong implementation of object serialization. A very convenient way to implement drag and drop and clipboard operations is to wrap up your objects in a COleDataSource object. This object can hold any data with a defined format or with a format that you can define and then it can be passed either to the clipboard by calling COleDataSource::SetClipboard or to the drag and drop handler by calling COleDataSource::DoDragDrop.

If you want to transfer a set of known objects between different parts of your applications, it is convenient to serialize them in a memory file and to wrap them up in a COleDataSource.

Let's start: This is my object:

class CLeopoldoOb : public CObject
{
    DECLARE_SERIAL(CLeopoldoOb)

// construction/destruction
public:
    CLeopoldoOb();
    // ....

protected:
    // some data....
    // some methods...
};

And this is my first version of the routine that wrapped up a set of those objects in the COleDataSource:

...

COleDataSource*	pDataSource = new COleDataSource;
if ( !pDataSource ) {
    return NULL;
}

// this is the memory file...
CSharedFile sf (GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT);
// this archive works on the memory file
CArchive    ar (&sf, CArchive::store);

// serialize the quantity
ar << m_nObjectCount;

for ( int i = 0; i < m_nObjectCount; i++ ) {
    CLeopoldoOb  leo;
    // now prepare the contents of the leopoldo object
    ...
    // object contains all data we need
    // serialize the object
    ar << &leo
}

ar.Flush ();
ar.Close ();

pDataSource->CacheGlobalData (g_cfLeopoldo, sf.Detach ());
pDataSource->DoDragDrop ();
if ( pDataSource->m_dwRef <= 1 ) {
    delete pDataSource;
}
else {
    pDataSource->ExternalRelease (); // !!!
}

...

And let's see the routine that unwraps the objects when they are dropped:

...

BOOL CMainFrame::OnDrop (COleDataObject* pDataObject, 
    DROPEFFECT dropEffect, CPoint point)
{
    if ( pDataObject->IsDataAvailable (g_cfLeopoldo) ) {
        CLeopoldoOb     *pOb;
        HGLOBAL         hMem = pDataObject->GetGlobalData (g_cfLeopoldo);
        CMemFile        mf;
        UINT            nCount;

        mf.Attach ((BYTE *)::GlobalLock (hMem), ::GlobalSize (hMem));
        CArchive ar (&mf, CArchive::load);

        // get the object count
        ar >> nCount;

        for ( UINT n = 0; n < nCount; n++ ) {
            try {
                // create the object out of the archive
                ar >> pOb;

                // now do what you have to do with the object
                ....
                // we do not need it any more...
                delete pOb;
            }
            catch { CException *pEx ) {
                // do some error handling
                pEx->Delete ();
            }

        }

        ar.Close ();
        mf.Detach ();
        ::GlobalUnlock (hMem);
        ::GlobalFree (hMem);
        return nCount > 0;
    }

    return FALSE;
}

What happened? Apparently this stuff worked, if you had only one object wrapped up. OK. Sometimes the application crashed but basically it worked. If instead more than one object was wrapped up, two strange things happened:

  • Only the first object was unwrapped
  • A CArchiveException with badIndex sometimes occurred

When tested under the debugger, I saw that the creation of the object from the serialization failed starting from the second time. Since there was definitively no error in the load routine, I reached the conclusion that the archive data must be messed up.

What Went Wrong?

After debugging in the profundities of CArchive I discovered that the process of storing dynamic objects is not as simple as I imagined it should be.

Obviously my error was during the creation of the archive. There are two important rules:

  1. The objects must be dynamically created (with CRuntimeClass::CreateObject).
  2. The objects must remain valid until the serialization has been finished.

If you are asking why, take a look into the source of CArchive and you will see that the archive stores additional information about those objects during its life. Furthermore the entire MFC seems to have knowledge about all dynamically created CObjects.

The Right Way

First of all we need a little helper class that will make life simpler:

class CAllocatedObArray : public CObArray
{
public:
    CAllocatedObArray           () { }
    virtual ~CAllocatedObArray  () { RemoveAll (); }

public:
    void  RemoveAll ();
};

void CAllocatedObArray::RemoveAll ()
{
    for ( int i = 0; i < GetSize (); i++ ) {
        CObject *pObject = GetAt (i);
        if ( pObject ) {
            delete pObject;
        }
    }
}

The following is the modified wrapper routine. You will see that all objects are created dynamically and stored into this array. After the serialization has finished, the array goes out of scope and our allocated objects will be automatically be destroyed.

...

COleDataSource*	pDataSource	= new COleDataSource;
if ( !pDataSource ) {
    return NULL;
}

// this is the memory file...
CSharedFile         sf (GMEM_MOVEABLE|GMEM_DDESHARE|GMEM_ZEROINIT);
// this archive works on the memory file
CArchive            ar (&sf, CArchive::store);
// this array holds our objects
CAllocatedObArray   tmpArray;
// This is needed to access the runtime class
CLeopoldoOb         leo;

// serialize the quantity
ar << m_nObjectCount;

for ( int i = 0; i < m_nObjectCount; i++ ) {
    CLeopoldoOb *pLeo = (CLeopoldoOb *) leo.GetRuntimeClass ()->CreateObject ();
    // store it in the array
    tmpArr.Add (pLeo);
    // now prepare the contents of the leopoldo object
    ...
    // object contains all data we need
    // serialize the object
    ar << pLeo
}

ar.Flush ();
ar.Close ();

pDataSource->CacheGlobalData (g_cfLeopoldo, sf.Detach ());
pDataSource->DoDragDrop ();
if ( pDataSource->m_dwRef <= 1 ) {
    delete pDataSource;
}
else {
    pDataSource->ExternalRelease (); // !!!
}

...

This works. Probably this will be nothing new for all experts among you, but since I did make this error after years of programming MFC, I hope that this article will help some beginner.

License

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


Written By
Product Manager PSI Logistics GmbH
Germany Germany
I started programming computers in 1979. After years of management and administration application programming, I started to work mainly in the telecommunication sector in 1986. While working at Cycos AG (formerly known as PP-COM GmbH) from 1992 to 1999 I was involved in the development of core and GUI components of their telematic server MRS for ISDN. After that I worked for a telecommunication company named Infitel International N.V. that produces software for open telecommunication services. After a long stop at Cycos AG, I worked for several other companies like Siemens Enterprise Communications, Axxom Software AG and PSI Logistics GmbH.

If you are curious about my other Computer related activities and previous projects, visit YeaSoft International

Comments and Discussions

 
GeneralClean-up code Pin
RedLars6-May-08 10:17
RedLars6-May-08 10:17 
Questiondrag&drop of files like the explorer Pin
Member 158781926-Feb-07 22:21
Member 158781926-Feb-07 22:21 
QuestionMFC is the right way to do serialization? Pin
Anonymous18-Mar-04 3:03
Anonymous18-Mar-04 3:03 
QuestionWhat about CF_HDROP's? Pin
Swinefeaster10-Nov-03 15:02
Swinefeaster10-Nov-03 15:02 
Hi there,

I read your article, and it seems you mention that you have to use your method when you want to cache multiple objects into the clipboard. I am trying to cache an CF_HDROP of filename handles, (to be dropping into the xp cd burning wizard). This used to work, but lately it stopped working (perhaps because of a Platform Sdk upgrade exposed something I was doing wrong).

So I got 2 for ya, if you can spare the time Smile | :)

1. Does your solution apply to CF_HDROP's?

2. Is there anything I'm doing wrong in the following code? I can't seem to see it. I tried replacing "CacheData" with "CacheGlobalData", but still have problems. CacheGlobalData fails in a call to ::GlobalSize(). If CacheData is used, CCmdTarget::~CCmdTarget() fails an assertion, ASSERT(m_dwRef <= 1), and the files don't get copied in.

<br />
void <br />
cPkpCollectFinishWizardPage::OnBeginDragDragList(NMHDR* Header, LRESULT* <br />
 pResult) <br />
{<br />
   const cPkpCollection* Collection = GrabCollection();<br />
<br />
   if(Collection)<br />
   {<br />
      cFilenameChain FilenameChain;<br />
      Collection->GetDropFiles(FilenameChain);<br />
<br />
      if(!FilenameChain.IsVoid())<br />
      {<br />
         NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)Header;<br />
<br />
         int item = pNMListView->iItem;<br />
<br />
         cSimpleListControl* List = &m_DragList;<br />
         CString Label = List->GetItemText(item, 0);<br />
         int labelLength = Label.GetLength() + 1;   // add one for the NULL<br />
<br />
         DWORD bitmapId = BMP_PHOTO_IMAGE;<br />
<br />
         HDROP dropHandle = FilenameChain.ConstructDropped();<br />
<br />
         if(dropHandle)<br />
         {<br />
            // Allocate our data object<br />
            COleDataSource* DataSource = new COleDataSource;<br />
<br />
            STGMEDIUM StgMedium;<br />
            StgMedium.tymed = TYMED_HGLOBAL;<br />
            StgMedium.hGlobal = (HGLOBAL)dropHandle;<br />
            StgMedium.pUnkForRelease = NULL;<br />
<br />
            DataSource->CacheData(CF_HDROP, &StgMedium);<br />
<br />
            PostMessage(UM_PKP_HANDLE_BEGIN_DRAG, (UINT)DataSource, <br />
             item);<br />
         }<br />
      }<br />
   }<br />
<br />
   *pResult = 0;<br />
}<br />
<br />
LRESULT<br />
cPkpCollectFinishWizardPage::OnHandleBeginDrag(WPARAM wParam, LPARAM lParam) <br />
{<br />
   COleDataSource* DataSource = (COleDataSource*)wParam;<br />
<br />
   int item = lParam;<br />
<br />
   if(!DataSource)<br />
   {<br />
      // Bad wParam.<br />
      ASSERT(false);<br />
   }<br />
   else<br />
   {<br />
      cPoint Point;<br />
      cPoint ClientPoint;<br />
      GetCursorPos(&Point);<br />
<br />
      ClientPoint = Point;<br />
<br />
      cSimpleListControl* List = &m_DragList;<br />
      ScreenToClient(&ClientPoint);<br />
<br />
      DROPEFFECT result = DataSource->DoDragDrop(DROPEFFECT_MOVE|DROPEFFECT_COPY, <br />
          NULL, m_DropSource);<br />
      }<br />
<br />
      delete DataSource;<br />
      DataSource = NULL;<br />
   }<br />
<br />
   return NOTHING;<br />
}<br />
<br />
ConstructDropped() does a <br />
<br />
         DWORD globalDataLength = sizeof(DROPFILES) + filesLength;<br />
         globalHandle = ::GlobalAlloc(GPTR, globalDataLength);   <br />
         char* FilesData = (char*)::GlobalLock(globalHandle);<br />
                                              <br />
         DROPFILES* DropFiles = (DROPFILES*)FilesData;<br />
         DropFiles->fNC = false;<br />
         DropFiles->fWide = false;<br />
         DropFiles->pFiles = sizeof(DROPFILES);<br />
         DropFiles->pt.x = 0;<br />
         DropFiles->pt.y = 0;<br />
<br />
... and puts the strings in...<br />


?

Any reply would be greatly appreciated. WTF | :WTF:

[b]yte your digital photos with [ae]phid [p]hotokeeper - www.aephid.com.
GeneralAllocation verification problem. Pin
Aurelian Georgescu26-Jun-03 5:18
Aurelian Georgescu26-Jun-03 5:18 
QuestionWhat about Serialize()? Pin
dshield21-Feb-03 16:37
dshield21-Feb-03 16:37 
AnswerRe: What about Serialize()? Pin
dshield21-Feb-03 16:51
dshield21-Feb-03 16:51 
Questionarrays of objects? Pin
The Ironduke15-May-01 21:56
The Ironduke15-May-01 21:56 
AnswerRe: arrays of objects? Pin
Leo Moll15-May-01 22:35
Leo Moll15-May-01 22:35 

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.