Created
February 13, 2022 23:31
-
-
Save edom18/db7ef65ec73548a883d705711187a1b2 to your computer and use it in GitHub Desktop.
Convert a struct array to a byte array with GCHandle
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.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