Skip to content

Instantly share code, notes, and snippets.

@alexanderbluhm
Created December 10, 2019 13:29
Show Gist options
  • Save alexanderbluhm/73d6b076f59e4092dc097c39b2962e27 to your computer and use it in GitHub Desktop.
Save alexanderbluhm/73d6b076f59e4092dc097c39b2962e27 to your computer and use it in GitHub Desktop.
Convertion between byte array and object
using System;
using System.Runtime.InteropServices;
namespace Utility
{
/*
*
struct Recipe
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 100)] // important to define the string length
public string name;
public int id;
public double weight;
}
*
*/
/// <summary>
/// Class to convert structures to byte arrays and parse byte arrays to objects.
/// </summary>
/// <typeparam name="T">Type of the struct to parse.</typeparam>
/// <example>
/// BinaryConverter<Recipe> binaryConverter = new BinaryConverter<Recipe>();
/// Recipe r = new Recipe() { id = 1, name = "Test123", weight = 1.0 };
/// var bytes = binaryConverter.GetBytes(r);
/// Recipe r1 = binaryConverter.FromBytes(bytes);
/// </example>
public class BinaryConverter<T> where T : new()
{
public byte[] GetBytes(T str)
{
int size = Marshal.SizeOf(str);
byte[] arr = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(str, ptr, true);
Marshal.Copy(ptr, arr, 0, size);
Marshal.FreeHGlobal(ptr);
return arr;
}
public T FromBytes(byte[] bytes)
{
T str = new T();
int size = Marshal.SizeOf(str);
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, ptr, size);
str = (T)Marshal.PtrToStructure(ptr, str.GetType());
Marshal.FreeHGlobal(ptr);
return str;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment