Skip to content

Instantly share code, notes, and snippets.

@edom18
Created February 13, 2022 23:31
Show Gist options
  • Save edom18/db7ef65ec73548a883d705711187a1b2 to your computer and use it in GitHub Desktop.
Save edom18/db7ef65ec73548a883d705711187a1b2 to your computer and use it in GitHub Desktop.
Convert a struct array to a byte array with GCHandle
[StructLayout(LayoutKind.Sequential)]
public struct Pixel32
{
public byte r;
public byte g;
public byte b;
public byte a;
}
// -----------------------
Pixel32[] pixels = new Pixel32[width * height];
// do something to the pixel array.
GCHandle handle = GCHandle.Alloc(pixels, GCHandleType.Pinned);
try
{
IntPtr pointer = handle.AddrOfPinnedObject();
byte[] destination = new byte[width * height * 4];
Marshal.Copy(pointer, destination, 0, destination.Length);
}
finally
{
if (handle.IsAllocated)
{
handle.Free();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment