Jerry Deng
Jerry Deng

Reputation: 467

Serializing a Pointer using MFC CArchive (with mfc100d.dll, CMemFile)

I am running into an issue serializing and deserializing pointer data in VS2010 VC++. Basically, the program was unable to serialize and deserialize a CObList * pointer data. The source code does the normal steps to handle the process:

1) MyObject was inherited from CObject;

2) We added DECLARE_SERIAL(MyObject) in the class declaration (1st line);

3) We added IMPLEMENT_SERIAL( MyObject, MyParentObject, SCHEMA_VERSION )

//Where MyParentObject is inherited from CObject (indirectly, there're a few more levels of objects), SCHEMA_VERSION is just a version control CONSTANT we use

4) Then we have overloaded

void MyObject::Serialize( CArchive& ar )
{
   BOOL b;
   .....
   ... (some other simple variables with default values)

   MyParentObject::Serialize(ar);

   if (ar.IsStoring())
   {
      ar << m_sTitle;
      ar << m_pObjectsList;
   }
   else
   {
      ar >> m_sTitle;
      ar >> m_pObjectsList;
   }
}

Note: MyParentObject::Serialize is implemented accordingly. CObList * m_pObjectsList; is declared properly in the header file.

The program threw an Access Violation (First-chance exception at 0x52e77b2c (mfc100d.dll) in MyApp.exe: 0xC0000005: Access violation reading location 0x00000004) when trying to deserialize from the "ar >> m_pObjectsList".

Then I started testing and changed the complex pointer m_pObjectsList to a simple pointer to CString. Same error occur at the same time when deserializing the pointer to CString. If I simply serialize and deserialize by CString (without the pointer), it works fine. It seems like some pointer serializing is broken.

Maybe MFC100d doesn't work well with W32 program in a 64Bit OS Debugger? This is causing problem both in Debug mode and Release mode. What's happening? I've exhausted my resources and any direction or inspiration is much appreciated. Thank you all ahead.

Upvotes: 1

Views: 2486

Answers (1)

Thomas Matthews
Thomas Matthews

Reputation: 57718

Pointers can't be serialized.

There is no guarantee that

  1. the application reading the file will have access to the same area of memory
  2. the OS will put the data in the same place
  3. the application reading the file will be placed in the same place in memory

One idea is to emulate pointers by using file offsets. Thus an object is located at a position in the file relative to the beginning. This is difficult.

A better idea is to write out all of the data and let the application reading the data place the data in memory. This also gives the application freedom to use any data structure it wants for storing the data.

Upvotes: 4

Related Questions