What would be a fast method to copy/convert an array
of Color32[]
values to a byte[]
buffer?
Color32
is
With modern .NET, you can use spans for this:
var bytes = MemoryMarshal.Cast<Color32, byte>(colors);
This gives you a Span<byte>
that covers the same data. The API is directly comparable to using vectors (byte[]
), but it isn't actually a vector, and there is no copy: you are directly accessing the original data. It is like an unsafe pointer coercion, but: entirely safe.
If you need it as a vector, ToArray
and copy methods exist for that.
Well why do you work with Color32?
byte[] Bytes = tex.GetRawTextureData(); . . . Tex.LoadRawTextureData(Bytes); Tex.Apply();
I ended up using this code:
using System.Runtime.InteropServices;
private static byte[] Color32ArrayToByteArray(Color32[] colors)
{
if (colors == null || colors.Length == 0)
return null;
int lengthOfColor32 = Marshal.SizeOf(typeof(Color32));
int length = lengthOfColor32 * colors.Length;
byte[] bytes = new byte[length];
GCHandle handle = default(GCHandle);
try
{
handle = GCHandle.Alloc(colors, GCHandleType.Pinned);
IntPtr ptr = handle.AddrOfPinnedObject();
Marshal.Copy(ptr, bytes, 0, length);
}
finally
{
if (handle != default(GCHandle))
handle.Free();
}
return bytes;
}
Which is fast enough for my needs.