将 Color32[] 数组快速复制到 byte[] 数组 [英] Fast copy of Color32[] array to byte[] array

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

问题描述

Color32[] 值的array复制/转换byte[]<的快速方法是什么?/代码>缓冲区?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 的新手.马里内斯库亚历山德鲁

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

这足以满足我的需要.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆