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

Color32[]array 复制/转换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; } 

谢谢,对不起,我是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; } 

这足以满足我的需求。