Created
July 17, 2014 14:08
-
-
Save kleberandrade/e4776f3f3a9836a80c89 to your computer and use it in GitHub Desktop.
Serialização e desserialização de estruturas em C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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