Click here to Skip to main content
15,901,035 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello!
1. I need to convert Object or struct to byte[](array).
2. Recently, I have found a certain code which ostensibly could convert object in a byte array. But for this purpose it was necessary to know the size of object. How can I receive the size of object?
It is necessary for me to use structure with type "string" inside!!!
Thankful in advance.
Posted
Updated 11-Feb-10 12:12pm
v3

C#
internal static StructureType ReadStructure<StructureType>(Stream Stream)
    where StructureType : struct
{
    int Length = Marshal.SizeOf(typeof(StructureType));
    byte[] Bytes = new byte[Length];
    Stream.Read(Bytes, 0, Length);
    IntPtr Handle = Marshal.AllocHGlobal(Length);
    Marshal.Copy(Bytes, 0, Handle, Length);
    StructureType Result = (StructureType)Marshal.PtrToStructure(Handle, typeof(StructureType));
    Marshal.FreeHGlobal(Handle);
    return Result;
}

internal static void WriteStructure(object Structure, Stream Stream)
{
    int Length = Marshal.SizeOf(Structure);
    byte[] Bytes = new byte[Length];
    IntPtr Handle = Marshal.AllocHGlobal(Length);
    Marshal.StructureToPtr(Structure, Handle, true);
    Marshal.Copy(Handle, Bytes, 0, Length);
    Marshal.FreeHGlobal(Handle);
    Stream.Write(Bytes, 0, Length);
}
 
Share this answer
 
Create class like this:

class MyClass
{
public int a;
public string text;

MyClass() { } // Necessary for XmlSerializer...
}
.........
.........
/*Instead of using a BinaryFormatter, use the XmlSerializer. This one can
serialize a class even if it is not marked as [Serializable], with the
restriction that it will only save the public fields and read-write
properties, and that it requires a default constructor.*/

public static byte[] ObjectToByteArray(Object obj//Our class instance
)
{
if (obj == null)
return null;
System.Xml.Serialization.XmlSerializer bf = new System.Xml.Serialization.XmlSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}

Enjoy!!!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900