Skip to content

Instantly share code, notes, and snippets.

@kleberandrade
Created July 17, 2014 14:08
Show Gist options
  • Save kleberandrade/e4776f3f3a9836a80c89 to your computer and use it in GitHub Desktop.
Save kleberandrade/e4776f3f3a9836a80c89 to your computer and use it in GitHub Desktop.
Serialização e desserialização de estruturas em C#
using System;
using System.Runtime.InteropServices;
internal static class StructSerialize<T>
{
public static T RawDeserialize(byte[] rawData)
{
return RawDeserialize(rawData, 0);
}
public static T RawDeserialize(byte[] rawData, int position)
{
int rawsize = Marshal.SizeOf(typeof(T));
if (rawsize > rawData.Length)
{
return default(T);
}
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(rawData, position, buffer, rawsize);
T obj = (T)Marshal.PtrToStructure(buffer, typeof(T));
Marshal.FreeHGlobal(buffer);
return obj;
}
public static byte[] RawSerialize(T item)
{
int rawSize = Marshal.SizeOf(typeof(T));
IntPtr buffer = Marshal.AllocHGlobal(rawSize);
Marshal.StructureToPtr(item, buffer, false);
byte[] rawData = new byte[rawSize];
Marshal.Copy(buffer, rawData, 0, rawSize);
Marshal.FreeHGlobal(buffer);
return rawData;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment