Created
May 24, 2013 10:45
-
-
Save diegofrata/5642669 to your computer and use it in GitHub Desktop.
Casting a struct from a byte array using C-style unions and without the unsafe keyword. Yay!
This file contains 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
[StructLayout(LayoutKind.Explicit)] | |
public struct ByteConverter<T> where T : struct | |
{ | |
#region Private Members | |
private static int SIZE_OF = Marshal.SizeOf(typeof(T)); | |
[FieldOffset(0)] | |
private byte[] _bytes; | |
[FieldOffset(0)] | |
private T[] _structs; | |
#endregion | |
#region Construction and Initialization | |
public ByteConverter(byte[] bytes) | |
{ | |
_structs = null; | |
_bytes = bytes; | |
} | |
#endregion | |
#region Public Properties | |
public int Length | |
{ | |
get { return _structs.Length / SIZE_OF; } | |
} | |
public T this[int index] | |
{ | |
get { return _structs[index * SIZE_OF]; } | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment