简体   繁体   中英

Fast copy of Color32[] array to byte[] array

What would be a fast method to copy/convert an array of Color32[] values to a byte[] buffer? Color32 is a struct from Unity 3D containing 4 bytes, R, G, B and A respectively . What I'm trying to accomplish is to send the rendered image from unity through a pipe to another application ( Windows Forms ). Currently I'm using this code:

private static byte[] Color32ArrayToByteArray(Color32[] colors)
{
    int length = 4 * colors.Length;
    byte[] bytes = new byte[length];
    IntPtr ptr = Marshal.AllocHGlobal(length);
    Marshal.StructureToPtr(colors, ptr, true);
    Marshal.Copy(ptr, bytes, 0, length);
    Marshal.FreeHGlobal(ptr);
    return bytes;
}

Thankyou and sorry, I'm new to StackOverflow. Marinescu Alexandru

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM