C++/CLI Code Snippet - Byte array to object

C++/CLI Code Snippet - Byte array to object

C++/CLI Code Snippet - Byte array to object

C++/CLI code snippet convert byte array to object. This function useful to convert back byte array data to its original object representation. This function can be use to deserialize those byte array data (Serialized) to their original objects.

Bookmark:

C++/CLI Code Snippet - Byte array to object

This .Net C++/CLI code snippet convert byte array to object. This function useful to convert back byte array data to its original object representation. Most common method to store binary data in database is as a byte array format. This function can be use to deserialize those byte array data (Serialized) to their original objects like image data ..etc. This function uses System.IO and System.Runtime.Serialization.Formatters.Binary name spaces to convert byte array to object. Modify the exception handling section as to your project requirements.

Note that it will be necessary to cast the returned generic Object from the deserialization method back into the original type of object you passed in to the serialization method originally.

System::Object ^ByteArrayToObject(array<System::Byte> ^_ByteArray)
{
    try
    {
        // convert byte array to memory stream
        System::IO::MemoryStream ^_MemoryStream = gcnew System::IO::MemoryStream(_ByteArray);

        // create new BinaryFormatter
        System::Runtime::Serialization::Formatters::Binary::BinaryFormatter ^_BinaryFormatter = gcnew System::Runtime::Serialization::Formatters::Binary::BinaryFormatter();

        // set memory stream position to starting point
        _MemoryStream->Position = 0;

        // Deserializes a stream into an object graph and return as a object.
        return _BinaryFormatter->Deserialize(_MemoryStream);
    }
    catch (Exception ^_Exception)
    {
        // Error
        Console::WriteLine("Exception caught in process: {0}", _Exception->ToString());
    }

    // Error occured, return null
    return nullptr;
}


Here is a simple example showing how to use above function (ByteArrayToObject). In this example we convert byte array variable (_ByteArray) to image and show the image in picturebox.

array<System::Byte> ^_ByteArray = .... some data ....;

pictureBox1->Image = safe_cast<Image^>(ByteArrayToObject("c:\\image-object.dat"));


C++/CLI Keywords Used:

  • MemoryStream
  • BinaryFormatter
  • Deserialize
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C++, CLI, Byte Array, Byte array to object, Binary Data, Deserialize, BinaryFormatter, Store binary data in database
  • Programming Language : C++/CLI

External Resources:

Leave a comment