Skip to content

Instantly share code, notes, and snippets.

@slimflem
Created September 1, 2013 21:29
Show Gist options
  • Save slimflem/6407436 to your computer and use it in GitHub Desktop.
Save slimflem/6407436 to your computer and use it in GitHub Desktop.
encode data to byte[]. in this case, IDataStructure is a marker interface only that is inherited by structs.
internal static byte[] EncodeToBytes(this IDataStructure data)
{
// get the unmanaged size of the data in bytes being marshalled.
var size = Marshal.SizeOf(data);
// allocate unmanaged memory of size bytes.
var ptr = Marshal.AllocHGlobal(size);
// marshall the data from managed to unmanaged memory.
// passing true as the last parameter allows all unmanaged
// memory allocations to be released during this operation
// as appropriate. See MSDN documentation.
Marshal.StructureToPtr(data, ptr, true);
// allocate a managed byte[] to be returned to the caller.
var array = new byte[size];
// copy the unmanaged memory into a managed byte array.
Marshal.Copy(ptr, array, 0, size);
// release the unmanaged memory.
Marshal.FreeHGlobal(ptr);
// return the managed byte[].
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment