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

浪子不回头ぞ 提交于 2019-12-18 06:57:00

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/21512259/fast-copy-of-color32-array-to-byte-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!