Search code examples
c#binaryfilespack

Is there an equivalent in C# to pack and unpack from Perl?


Is there some library who permit to do the same as pack and unpack Perl function?

With a template list as http://perldoc.perl.org/functions/pack.html,

pack is for converting a list into a binary representation
unpack is for converting binary structure into normal Perl variables

To be brief:

I give a byte[] array, a template to parse the packet, and variable that will receive extracted data.

It seems Mono is providing such a feature, but templates are not the same, see http://www.mono-project.com/Mono_DataConvert#Obtaining_Mono.DataConvert.


Solution

  • It seems that what you want to know about is Binary Serialization. From the link;

    Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created.

    A more concrete example of Binary Serialization for C# (targeting .NET Framework 4.5) can be found here. Brief synopsis; you must annotate the class you wish to serialize and deserialize with a [Serializable] tag, and then use a Formatter instance to actually do the serialization/deserialization.

    So in Perl where you can simply say:

    pack TEMPLATE,LIST
    

    In C# you'll need the following:

    [Serializable]
    public class MyObject {
      public int n1 = 0;
      public int n2 = 0;
      public String str = null;
    }
    
    // ... And in some other class where you have you application logic
    
    public void pack()
    {
    
        MyObject obj = new MyObject();
        obj.n1 = 1;
        obj.n2 = 24;
        obj.str = "Some String";
        IFormatter formatter = new BinaryFormatter();
        Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
        formatter.Serialize(stream, obj);
        stream.Close();
    }
    

    To address the idea that you are going to want to control the serialization template, you'll likely need to implement ISerializable yourself. Here's a MSDN article about custom binary serialization. By implementing the interface yourself, you gain a very high amount of control of the binary template in exchange for a high amount of complexity in ensuring functionality.