color32 []数组的快速副本到字节[]数组



copy/convert Color32[]值的 array CC_1值将是什么快速方法? Color32是包含4 bytes, R, G, B and A respectively的Unity 3D的结构。我要完成的工作是将渲染图像从统一发送到另一个应用程序(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;
}

谢谢,对不起,我是新手stackoverflow。Marinescu Alexandru

我最终使用了此代码:

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;
}

这足以满足我的需求。

使用现代.NET,您可以使用跨度:

var bytes = MemoryMarshal.Cast<Color32, byte>(colors);

这为您提供了涵盖相同数据的Span<byte>。API与使用向量(byte[])直接可比,但实际上不是向量,并且没有复制:您直接访问了原始数据。这就像一个不安全的指针胁迫,但是:完全安全。

如果您需要作为向量,ToArray和复制方法为此。

好吧,为什么您要使用color32?

byte [] bytes = tex.getRawTextredAta();。。。Tex.LoadRawtexturedata(字节);Tex.Apply();

最新更新