Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C++/CLI
Article

Serialization Primer - MC++

Rate me:
Please Sign up or sign in to vote.
4.81/5 (17 votes)
25 May 20023 min read 176.8K   2.6K   31   20
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.

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.

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.

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.
 

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.

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.

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

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


Written By
United States United States
Nish Nishant is a technology enthusiast from Columbus, Ohio. He has over 20 years of software industry experience in various roles including Chief Technology Officer, Senior Solution Architect, Lead Software Architect, Principal Software Engineer, and Engineering/Architecture Team Leader. Nish is a 14-time recipient of the Microsoft Visual C++ MVP Award.

Nish authored C++/CLI in Action for Manning Publications in 2005, and 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 experienced in technology leadership, solution architecture, software architecture, cloud development (AWS and Azure), REST services, software engineering best practices, CI/CD, mentoring, and directing all stages of software development.

Nish's Technology Blog : voidnish.wordpress.com

Comments and Discussions

 
QuestionSerializing class with unmanaged base class Pin
EricFowler8-Mar-07 13:46
EricFowler8-Mar-07 13:46 
GeneralSerialization Issues Pin
Vsunkara2-Aug-06 5:37
Vsunkara2-Aug-06 5:37 
GeneralHello Pin
Raj_Sen28-Feb-06 12:40
Raj_Sen28-Feb-06 12:40 
Hi...

If any body have MDI serial port programming in C++ ...Please can u send me a Zip file or code,,,,It will be very help full in my project.I like to hear from u guys very soon..

Cheers
Raj

Raj
GeneralWoohoo, oh wait.... Pin
Nigel Atkinson9-Mar-05 13:38
Nigel Atkinson9-Mar-05 13:38 
QuestionI imagine it's as easy in C# and VB.NET? Pin
Jörgen Sigvardsson26-Sep-02 11:45
Jörgen Sigvardsson26-Sep-02 11:45 
GeneralNice Article Pin
Kannan Kalyanaraman27-May-02 9:05
Kannan Kalyanaraman27-May-02 9:05 
GeneralRe: Nice Article Pin
Nish Nishant27-May-02 14:46
sitebuilderNish Nishant27-May-02 14:46 
GeneralPerfect editing and formatting ;-) Pin
Nish Nishant26-May-02 0:51
sitebuilderNish Nishant26-May-02 0:51 
GeneralRe: Perfect editing and formatting ;-) Pin
Shog926-May-02 8:23
sitebuilderShog926-May-02 8:23 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish Nishant26-May-02 13:20
sitebuilderNish Nishant26-May-02 13:20 
GeneralRe: Perfect editing and formatting ;-) Pin
Shog926-May-02 14:22
sitebuilderShog926-May-02 14:22 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish Nishant26-May-02 14:32
sitebuilderNish Nishant26-May-02 14:32 
GeneralRe: Perfect editing and formatting ;-) Pin
PJ Arends26-May-02 14:51
professionalPJ Arends26-May-02 14:51 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish Nishant26-May-02 14:52
sitebuilderNish Nishant26-May-02 14:52 
GeneralRe: Perfect editing and formatting ;-) Pin
Matt Newman26-May-02 15:28
Matt Newman26-May-02 15:28 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish Nishant26-May-02 15:33
sitebuilderNish Nishant26-May-02 15:33 
GeneralRe: Perfect editing and formatting ;-) Pin
Matt Newman26-May-02 16:25
Matt Newman26-May-02 16:25 
GeneralRe: Perfect editing and formatting ;-) Pin
Nish Nishant26-May-02 17:14
sitebuilderNish Nishant26-May-02 17:14 
General*ouch*! Pin
Shog926-May-02 16:38
sitebuilderShog926-May-02 16:38 
GeneralRe: *ouch*! Pin
Nish Nishant26-May-02 17:15
sitebuilderNish Nishant26-May-02 17: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.