本文介绍了Color32 []数组到byte []数组的快速拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

复制/转换一个数组的快速方法 Color32 [] 值到 byte [] buffer?
Color32 是Unity 3D的结构,包含 4个字节,R,G,B和A 。
我想要完成的是将渲染的图像从unity通过管道发送到另一个应用程序( Windows Forms )。目前我使用的代码:

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

谢谢对不起,我是StackOverflow的新人。
Marinescu Alexandru

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

推荐答案

我最后使用这段代码:

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

这足够满足我的需要。

这篇关于Color32 []数组到byte []数组的快速拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 18:42