Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How to convert any object to byte[] without marking it Serializable or DataContract?

How to convert any object to byte[] without marking it Serializable or DataContract?

Scheduled Pinned Locked Moved C#
tutorialquestionlearning
10 Posts 2 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • 1 Offline
    1 Offline
    1eyhk1
    wrote on last edited by
    #1

    hello How to convert any object to byte[] without marking it Serializable or DataContract? Of course this would work but you'd need to mark myObj class Serializable (I'm lazy dont want handcode serializable for big classes sorry) using (System.IO.MemoryStream returnStm = new System.IO.MemoryStream()) { BinaryFormatter ftm = new BinaryFormatter(); ftm.Serialize(returnStm , myObj); return returnStm .ToArray(); // this would return byte[] } Anyone who can tell me how I can commit such crime? Thank you

    G 1 Reply Last reply
    0
    • 1 1eyhk1

      hello How to convert any object to byte[] without marking it Serializable or DataContract? Of course this would work but you'd need to mark myObj class Serializable (I'm lazy dont want handcode serializable for big classes sorry) using (System.IO.MemoryStream returnStm = new System.IO.MemoryStream()) { BinaryFormatter ftm = new BinaryFormatter(); ftm.Serialize(returnStm , myObj); return returnStm .ToArray(); // this would return byte[] } Anyone who can tell me how I can commit such crime? Thank you

      G Offline
      G Offline
      Gonzalo Cao
      wrote on last edited by
      #2

      Hi, I do this and it works for me. public byte[] RawSerialize(object item, Type anyType) { int structSize = Marshal.SizeOf(item); IntPtr ptr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(item, ptr, true); byte[] bff = new byte[structSize]; Marshal.Copy(ptr, bff, 0, structSize); Marshal.FreeHGlobal(ptr); return bff; }

      1 2 Replies Last reply
      0
      • G Gonzalo Cao

        Hi, I do this and it works for me. public byte[] RawSerialize(object item, Type anyType) { int structSize = Marshal.SizeOf(item); IntPtr ptr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(item, ptr, true); byte[] bff = new byte[structSize]; Marshal.Copy(ptr, bff, 0, structSize); Marshal.FreeHGlobal(ptr); return bff; }

        1 Offline
        1 Offline
        1eyhk1
        wrote on last edited by
        #3

        Many thanks I don't have time test it now but already feel my knowledge increase

        1 Reply Last reply
        0
        • G Gonzalo Cao

          Hi, I do this and it works for me. public byte[] RawSerialize(object item, Type anyType) { int structSize = Marshal.SizeOf(item); IntPtr ptr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(item, ptr, true); byte[] bff = new byte[structSize]; Marshal.Copy(ptr, bff, 0, structSize); Marshal.FreeHGlobal(ptr); return bff; }

          1 Offline
          1 Offline
          1eyhk1
          wrote on last edited by
          #4

          Hello Gonzalo Do you have the code for reverse process as well please please please?

          G 1 Reply Last reply
          0
          • 1 1eyhk1

            Hello Gonzalo Do you have the code for reverse process as well please please please?

            G Offline
            G Offline
            Gonzalo Cao
            wrote on last edited by
            #5

            public static object RawDeserialize(byte[] rawdatas, Type anytype)
            {
            int rawsize = Marshal.SizeOf(anytype);

               if (rawsize != rawdatas.Length)
               { return null; }
            
               IntPtr buffer = Marshal.AllocHGlobal(rawsize);
            
               Marshal.Copy(rawdatas, 0, buffer, rawsize);
            
               object retobj = Marshal.PtrToStructure(buffer, anytype);
            
               Marshal.FreeHGlobal(buffer);
               return retobj;
             }
            

            Here it is :)

            1 1 Reply Last reply
            0
            • G Gonzalo Cao

              public static object RawDeserialize(byte[] rawdatas, Type anytype)
              {
              int rawsize = Marshal.SizeOf(anytype);

                 if (rawsize != rawdatas.Length)
                 { return null; }
              
                 IntPtr buffer = Marshal.AllocHGlobal(rawsize);
              
                 Marshal.Copy(rawdatas, 0, buffer, rawsize);
              
                 object retobj = Marshal.PtrToStructure(buffer, anytype);
              
                 Marshal.FreeHGlobal(buffer);
                 return retobj;
               }
              

              Here it is :)

              1 Offline
              1 Offline
              1eyhk1
              wrote on last edited by
              #6

              Many thanks Master Cao! If I still can't get my WCF contract working I may just try serialize/de-serialize whole deal to byte[]

              G 1 Reply Last reply
              0
              • 1 1eyhk1

                Many thanks Master Cao! If I still can't get my WCF contract working I may just try serialize/de-serialize whole deal to byte[]

                G Offline
                G Offline
                Gonzalo Cao
                wrote on last edited by
                #7

                You welcome. Good luck with you project.

                1 1 Reply Last reply
                0
                • G Gonzalo Cao

                  You welcome. Good luck with you project.

                  1 Offline
                  1 Offline
                  1eyhk1
                  wrote on last edited by
                  #8

                  Oh bummer {"Type 'XXXXX.MyAccount' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed."} I suspect this is because MyAccount is actually a complex hierarchy containing a child collection... class MyAccount { ... public List<Invoicesgt; GroupList; } Eekkk... I was going to wire down an array of accounts (i.e. MyAccount[]) but now can't even wire down one single MyAccount... I desparation I tried this: using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, result); byte[] BinAcct = stream.ToArray()); } But even then I ran into runtime exception, complaint was that class is not marked serializable (Although marked DataContract), looks like I got lucky with DataContractSerializer dataContractSerializer = new DataContractSerializer(Acct.GetType()); using (MemoryStream memoryStream = new MemoryStream()) { dataContractSerializer.WriteObject(memoryStream, Acct); btAccountSet = new byte[memoryStream.Length]; Array.Copy(memoryStream.GetBuffer(), btAccountSet, btAccountSet.Length); } This finally get the job done (only serialization part, still stuck during deserialization). 1. Serialize side: DataContractSerializer serial = new DataContractSerializer(Acct.GetType()); using (MemoryStream memoryStream = new MemoryStream()) { serial.WriteObject(memoryStream, oAcct); btPayload = new byte[memoryStream.Length]; Array.Copy(memoryStream.GetBuffer(), btPayload, btPayload.Length); } 2. Deserialize side: byte[] raw = (byte[]) GetPayload(); serial = new DataContractSerializer(typeof(MyAccount)); using (MemoryStream memoryStream = new MemoryStream(raw)) { memoryStream.Seek(0, SeekOrigin.Begin); oAcct = (MyAccount) serial.ReadObject(memoryStream); } So, all good sending a single object, but still need to attempt sending/serializing a list of MyAccount (with subclasses) Thanks

                  modified on Saturday, August 21, 2010 1:46 AM

                  G 1 Reply Last reply
                  0
                  • 1 1eyhk1

                    Oh bummer {"Type 'XXXXX.MyAccount' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed."} I suspect this is because MyAccount is actually a complex hierarchy containing a child collection... class MyAccount { ... public List<Invoicesgt; GroupList; } Eekkk... I was going to wire down an array of accounts (i.e. MyAccount[]) but now can't even wire down one single MyAccount... I desparation I tried this: using (System.IO.MemoryStream stream = new System.IO.MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, result); byte[] BinAcct = stream.ToArray()); } But even then I ran into runtime exception, complaint was that class is not marked serializable (Although marked DataContract), looks like I got lucky with DataContractSerializer dataContractSerializer = new DataContractSerializer(Acct.GetType()); using (MemoryStream memoryStream = new MemoryStream()) { dataContractSerializer.WriteObject(memoryStream, Acct); btAccountSet = new byte[memoryStream.Length]; Array.Copy(memoryStream.GetBuffer(), btAccountSet, btAccountSet.Length); } This finally get the job done (only serialization part, still stuck during deserialization). 1. Serialize side: DataContractSerializer serial = new DataContractSerializer(Acct.GetType()); using (MemoryStream memoryStream = new MemoryStream()) { serial.WriteObject(memoryStream, oAcct); btPayload = new byte[memoryStream.Length]; Array.Copy(memoryStream.GetBuffer(), btPayload, btPayload.Length); } 2. Deserialize side: byte[] raw = (byte[]) GetPayload(); serial = new DataContractSerializer(typeof(MyAccount)); using (MemoryStream memoryStream = new MemoryStream(raw)) { memoryStream.Seek(0, SeekOrigin.Begin); oAcct = (MyAccount) serial.ReadObject(memoryStream); } So, all good sending a single object, but still need to attempt sending/serializing a list of MyAccount (with subclasses) Thanks

                    modified on Saturday, August 21, 2010 1:46 AM

                    G Offline
                    G Offline
                    Gonzalo Cao
                    wrote on last edited by
                    #9

                    Were you able to fix it?? With the sample code you've posted I was not able to find the problem.

                    1 1 Reply Last reply
                    0
                    • G Gonzalo Cao

                      Were you able to fix it?? With the sample code you've posted I was not able to find the problem.

                      1 Offline
                      1 Offline
                      1eyhk1
                      wrote on last edited by
                      #10

                      hey yes, many thanks, working now and I just dodged a tight deadline! (Code I posted actually works, forgot to remove "Bummer" as initially when I posted the reply I was still having problem) Thanks very much!

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups