将array
个Color32[]
值复制/转换到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
答案 0 :(得分:3)
我最终使用了这段代码:
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;
}
这足以满足我的需求。
答案 1 :(得分:1)
使用现代.NET,您可以为此使用跨度:
var bytes = MemoryMarshal.Cast<Color32, byte>(colors);
这将为您提供一个涵盖相同数据的Span<byte>
。该API可直接与使用向量(byte[]
)相提并论,但实际上不是向量,并且没有副本:您可以直接访问原始数据。就像不安全的指针强制一样,但是:完全安全。
如果需要作为向量,则ToArray
和复制方法就可以使用。
答案 2 :(得分:-1)
那么为什么要使用Color32?
byte [] Bytes = tex.GetRawTextureData(); 。 。 。 Tex.LoadRawTextureData(Bytes); Tex.Apply();