-
October 27th, 2013, 08:23 PM
#1
Converting an object to a byte stream
I'm trying to convert an object to a byte stream and I'm using the code below to do it
Code:
public static byte[] ObjectToByteArray(System.Object obj)
{
MemoryStream fs = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, obj);
return fs.ToArray();
}
catch (Exception e)
{
Debug.Log("Exception sending friend request: " + e.Message);
return null;
}
finally
{
fs.Close();
}
}
The problem is that this puts a large C# header on the front of the byte stream. Is there a way to determine the size of the header, so when I send the stream over a socket, I can skip sending the header? Or better yet, not generate the header at all?
-
October 28th, 2013, 01:44 PM
#2
Re: Converting an object to a byte stream
-
October 28th, 2013, 08:47 PM
#3
Re: Converting an object to a byte stream
I'm not sure how I'd use that, but after a little more searching, I found another approach using Marshal.
Code:
public static byte[] ObjectToByteArray(System.Object obj)
{
int size = Marshal.SizeOf(obj);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
This required me to add some tags to the class, but it worked.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|