Click here to Skip to main content
13,288,104 members (55,692 online)
Click here to Skip to main content
Add your own
alternative version

Stats

158.3K views
2.6K downloads
31 bookmarked
Posted 25 May 2002

Serialization Primer - MC++

, 25 May 2002
Rate this:
Please Sign up or sign in to vote.
A basic introduction to serialization using Managed C++

Introduction

Serialization means taking objects and converting them into a form by which they can be stored on disk or transferred across the network. The advantage here is that objects can persist their state. Which means you can actually save an object to disk, this process is called serialization, and later you can read the data back to get the same object, this process is called deserialization. Serialization is used quite extensively in .NET remoting. The actual process of serialization basically involves converting all the members of the class along with the required meta data into  bytes which are then dumped to disk or to a socket. Later during deserialization, these bytes are converted back to the original object. The bytes are in the form of a stream, meaning they can be read and written as a stream of bytes. They don't necessarily need to arrive  all at once.

First Program

In this first program we'll see how to make a serializable class. I have a class called CData. I have marked the class as serializable by marking it with the [Serializable] attribute. The serialized data has to be encoded in some particular format. Thus we also need a class to specify what kind of formatting will be used to encode the byte stream.  Here I have used the BinaryFormatter class which uses binary format as the name implies. I have used the Serialize member function to serialize the object  to a stream and I have used the Deserialize member function to deserialize the stream back to the object.

<pre lang=mc++>#include "stdafx.h" #using <mscorlib.dll> using namespace System; using namespace System::Runtime::Serialization; using namespace System::Runtime::Serialization::Formatters::Binary; using namespace System::IO; [Serializable] __gc class CData { private: String* m_name; Int32 m_age; public: __property String* get_Name() { return m_name; } __property void set_Name(String* s) { m_name = s; } __property Int32 get_Age() { return m_age; } __property void set_Age(Int32 i) { m_age = i; } CData() { m_name="Default"; m_age=0; } }; int wmain(int argc, char **argv) { if(argc==1) { Console::WriteLine("Usage:- Serialize00 [L/S]"); return 0; } if(argv[1][0]=='S') { Console::WriteLine("Saving to file"); CData *data = new CData(); data->Name = "Johnny Bravo"; data->Age = 24; FileStream *fs = new FileStream("data.txt" , FileMode::Create, FileAccess::ReadWrite); BinaryFormatter *bf = new BinaryFormatter(); //This single call will serialize the object //to a byte stream bf->Serialize(fs,data); fs->Close(); } else if(argv[1][0]=='L') { Console::WriteLine("Loading from file"); CData *data; FileStream *fs = new FileStream("data.txt" , FileMode::Open, FileAccess::ReadWrite); //This single call will deserialize the byte //stream back to a copy of the original object BinaryFormatter *bf = new BinaryFormatter(); data = (CData*) bf->Deserialize(fs); Console::WriteLine("data->Name is {0}", data->Name); Console::WriteLine("data->Age is {0}", data->Age.ToString()); fs->Close(); } else { Console::WriteLine("Unknown option"); } return 0; }

Second Program

Sometimes we might not want to persist all members of an object. In such situations we can actually use the [NonSerialized] attribute to mark certain members as non-serialized. This means they won't be persisted. But I intend to show you how to achieve this in a different way by implementing the ISerializable interface which gives us a lot more control in the way our object is serialized and deserialized. Well, we don't do anything special except that we derive our class from ISerializable . ISerializable has one member function GetObjectData  which we will have to implement. This method is used for data serialization. We also need to implement an overload of the constructor to handle deserialization.

<pre lang=mc++> void GetObjectData(SerializationInfo *si, StreamingContext sc) { si->AddValue("m_name",m_name); si->AddValue("m_age",m_age); }

As you can see, we have a SerializationInfo class which holds the data required to serialize the object. We use the AddValue method to add two named values. We leave out the member which we don't need to serialize. This is a rather simple usage of this technique. We could do further customization here if we wanted to.

<pre lang=mc++> CData(SerializationInfo *si, StreamingContext sc) { m_name = si->GetString("m_name"); m_age = si->GetInt32("m_age"); }

And here we have the special constructor that is used during deserialization. As you can see, we use the various  GetXXXX functions to retrieve our data back. It might puzzle you why this was done this way instead of providing us with a DeSerializeData function. But Microsoft probably have their own funny whims. One disadvantage is that you won't get any compiler errors even if you forget to write this special constructor. But an exception will get thrown during runtime. So the bug won't remain hidden for too long.
 

<pre lang=mc++>#include "stdafx.h" #using <mscorlib.dll> using namespace System; using namespace System::Runtime::Serialization; using namespace System::Runtime::Serialization::Formatters::Binary; using namespace System::IO; [Serializable] __gc class CData : public ISerializable { private: String* m_name; Int32 m_age; String* m_dontsave; public: __property String* get_Name() { return m_name; } __property void set_Name(String* s) { m_name = s; } __property Int32 get_Age() { return m_age; } __property void set_Age(Int32 i) { m_age = i; } __property String* get_DontSave() { return m_dontsave; } __property void set_DontSave(String* s) { m_dontsave = s; } void GetObjectData(SerializationInfo *si, StreamingContext sc) { si->AddValue("m_name",m_name); si->AddValue("m_age",m_age); } CData() { m_name="Default"; m_dontsave = "Default"; } protected: CData(SerializationInfo *si, StreamingContext sc) { m_name = si->GetString("m_name"); m_age = si->GetInt32("m_age"); } }; int wmain(int argc, char **argv) { if(argc==1) { Console::WriteLine("Usage:- Serialize01 [L/S]"); return 0; } if(argv[1][0]=='S') { Console::WriteLine("Saving to file"); CData *data = new CData(); data->Name = "Johnny Bravo"; data->Age = 24; data->DontSave = "Hello World"; FileStream *fs = new FileStream("data.txt" , FileMode::Create, FileAccess::ReadWrite); BinaryFormatter *bf = new BinaryFormatter(); bf->Serialize(fs,data); fs->Close(); } else if(argv[1][0]=='L') { Console::WriteLine("Loading from file"); CData *data; FileStream *fs = new FileStream("data.txt" , FileMode::Open, FileAccess::ReadWrite); BinaryFormatter *bf = new BinaryFormatter(); data = (CData*) bf->Deserialize(fs); Console::WriteLine("data->Name is {0}", data->Name); Console::WriteLine("data->Age is {0}", data->Age.ToString()); Console::WriteLine("data->DontSave is {0}", data->DontSave); fs->Close(); } else { Console::WriteLine("Unknown option"); } return 0; }

Third Program

When you derive a class from your serializable class, you must make sure to mark the derived class as [Serializable] too. Else you'll get a compiler error. You must also implement both variations of the constructors, as well as implement GetObjectData(). In GetObjectData you must remember to call the base class function first.

<pre lang=mc++> void GetObjectData(SerializationInfo *si, StreamingContext sc) { CData::GetObjectData(si,sc); si->AddValue("m_new",m_new); }

Each of the constructors must also call their corresponding base class constructors. Otherwise there will be problems during deserialization.

<pre lang=mc++> CData2() : CData() { m_new = "Default"; } CData2(SerializationInfo *si, StreamingContext sc) : CData(si,sc) { m_new = si->GetString("m_new"); }

<pre lang=mc++>#include "stdafx.h" #using <mscorlib.dll> using namespace System; using namespace System::Runtime::Serialization; using namespace System::Runtime::Serialization::Formatters::Binary; using namespace System::IO; [Serializable] __gc class CData : public ISerializable { private: String* m_name; Int32 m_age; String* m_dontsave; public: __property String* get_Name() { return m_name; } __property void set_Name(String* s) { m_name = s; } __property Int32 get_Age() { return m_age; } __property void set_Age(Int32 i) { m_age = i; } __property String* get_DontSave() { return m_dontsave; } __property void set_DontSave(String* s) { m_dontsave = s; } void GetObjectData(SerializationInfo *si, StreamingContext sc) { si->AddValue("m_name",m_name); si->AddValue("m_age",m_age); } CData() { m_name="Default"; m_dontsave = "Default"; } protected: CData(SerializationInfo *si, StreamingContext sc) { m_name = si->GetString("m_name"); m_age = si->GetInt32("m_age"); } }; [Serializable] __gc class CData2 : public CData { private: String *m_new; public: __property String* get_NewName() { return m_new; } __property void set_NewName(String* s) { m_new = s; } CData2() : CData() { m_new = "Default"; } void GetObjectData(SerializationInfo *si, StreamingContext sc) { CData::GetObjectData(si,sc); si->AddValue("m_new",m_new); } protected: CData2(SerializationInfo *si, StreamingContext sc) : CData(si,sc) { m_new = si->GetString("m_new"); } }; int wmain(int argc, char **argv) { if(argc==1) { Console::WriteLine("Usage:- Serialize02 [L/S]"); return 0; } if(argv[1][0]=='S') { Console::WriteLine("Saving to file"); CData2 *data = new CData2(); data->Name = "Johnny Bravo"; data->Age = 24; data->DontSave = "Hello World"; data->NewName = "Nish"; FileStream *fs = new FileStream("data.txt" , FileMode::Create, FileAccess::ReadWrite); BinaryFormatter *bf = new BinaryFormatter(); bf->Serialize(fs,data); fs->Close(); } else if(argv[1][0]=='L') { Console::WriteLine("Loading from file"); CData2 *data; FileStream *fs = new FileStream("data.txt" , FileMode::Open, FileAccess::ReadWrite); BinaryFormatter *bf = new BinaryFormatter(); data = (CData2*) bf->Deserialize(fs); Console::WriteLine("data->Name is {0}", data->Name); Console::WriteLine("data->Age is {0}", data->Age.ToString()); Console::WriteLine("data->DontSave is {0}", data->DontSave); Console::WriteLine("data->NewName is {0}", data->NewName); fs->Close(); } else { Console::WriteLine("Unknown option"); } return 0; }

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Nish Nishant
United States United States
Nish Nishant is the Principal Software Architect/Consultant for Ganymede Software Solutions LLC, and is based out of Columbus, Ohio. He has over 17 years of software industry experience in various roles including Lead Software Architect, Principal Software Engineer, and Product Manager. Nish was a Microsoft Visual C++ MVP between 2002 and 2015.

Nish is an industry acknowledged expert in the Microsoft technology stack. He authored C++/CLI in Action for Manning Publications in 2005, and had previously co-authored Extending MFC Applications with the .NET Framework for Addison Wesley in 2003. In addition, he has over 140 published technology articles on CodeProject.com and another 250+ blog articles on his WordPress blog. Nish is vastly experienced in team management, mentoring teams, and directing all stages of software development.

Contact Nish : If you are interested in hiring Nish as a consultant, you can reach him via his google email id voidnish.

Company Website : www.ganymedesoftwaresolutions.com

You may also be interested in...

Comments and Discussions

 
QuestionSerializing class with unmanaged base class Pin
EricFowler8-Mar-07 14:46
memberEricFowler8-Mar-07 14:46 
GeneralSerialization Issues Pin
Vsunkara2-Aug-06 6:37
memberVsunkara2-Aug-06 6:37 
GeneralHello Pin
Raj_Sen28-Feb-06 13:40
memberRaj_Sen28-Feb-06 13:40 
GeneralWoohoo, oh wait.... Pin
Merlinblack9-Mar-05 14:38
memberMerlinblack9-Mar-05 14:38 
Just prefect for the game I'm writing. Oh wait, I'm not using .NET, but hang on I can! Expect it in the coming up millennium. Its really an excuse to play with (and learn):

OpenGL
OpenAL
OpenTNL
and now some .NET chucked in.;P

I like your articles, to the point, easy to understand, shorter (only just) than my attention span Poke tongue | ;-P , and there on CP which is easier that MSDN to find stuff in.

"Land a'hoy!" * CRASH * "I should av said that sooner eh?" - Eckles, The Goon Show
QuestionI imagine it's as easy in C# and VB.NET? Pin
Jörgen Sigvardsson26-Sep-02 12:45
memberJörgen Sigvardsson26-Sep-02 12:45 
GeneralNice Article Pin
Kannan Kalyanaraman27-May-02 10:05
memberKannan Kalyanaraman27-May-02 10:05 
GeneralRe: Nice Article Pin
Nish - Native CPian27-May-02 15:46
memberNish - Native CPian27-May-02 15:46 
GeneralPerfect editing and formatting ;-) Pin
Nish - Native CPian26-May-02 1:51
memberNish - Native CPian26-May-02 1:51 
GeneralRe: Perfect editing and formatting ;-) Pin
Shog926-May-02 9:23
memberShog926-May-02 9:23 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish - Native CPian26-May-02 14:20
memberNish - Native CPian26-May-02 14:20 
GeneralRe: Perfect editing and formatting ;-) Pin
Shog926-May-02 15:22
memberShog926-May-02 15:22 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish - Native CPian26-May-02 15:32
memberNish - Native CPian26-May-02 15:32 
GeneralRe: Perfect editing and formatting ;-) Pin
PJ Arends26-May-02 15:51
memberPJ Arends26-May-02 15:51 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish - Native CPian26-May-02 15:52
memberNish - Native CPian26-May-02 15:52 
GeneralRe: Perfect editing and formatting ;-) Pin
Matt Newman26-May-02 16:28
memberMatt Newman26-May-02 16:28 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish - Native CPian26-May-02 16:33
memberNish - Native CPian26-May-02 16:33 
GeneralRe: Perfect editing and formatting ;-) Pin
Matt Newman26-May-02 17:25
memberMatt Newman26-May-02 17:25 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish - Native CPian26-May-02 18:14
memberNish - Native CPian26-May-02 18:14 
General*ouch*! Pin
Shog926-May-02 17:38
memberShog926-May-02 17:38 
GeneralRe: *ouch*! Pin
Nish - Native CPian26-May-02 18:15
memberNish - Native CPian26-May-02 18:15 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171207.1 | Last Updated 26 May 2002
Article Copyright 2002 by Nish Nishant
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid