快速将Color32 []数组复制到byte []数组

use*_*058 4 c# struct copy marshalling unity-game-engine

会是怎样一个快速的方法来拷贝/转换一个arrayColor32[]值的byte[]缓冲? Color32是Unity 3D中包含的结构4 bytes, R, G, B and A respectively。我要完成的工作是将渲染的图像从整体通过管道发送到另一个应用程序(Windows Forms)。目前,我正在使用以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

谢谢,抱歉,我是StackOverflow的新手。Marinescu Alexandru

use*_*058 6

我最终使用了以下代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

这足以满足我的需求。