将2d结构数组复制到byte []

时间:2011-04-13 14:46:33

标签: c# arrays marshalling

我有类似的东西:

[StructLayout(LayoutKind.Explicit)]
public struct PixelColorRGBA
{
    [FieldOffset(0)]
    public UInt32 ColorBGRA;
    [FieldOffset(0)]
    public byte Blue;
    [FieldOffset(1)]
    public byte Green;
    [FieldOffset(2)]
    public byte Red;
    [FieldOffset(3)]
    public byte Alpha;
}

PixelColorRGBA[w, h]复制到byte[w * h * 4]的最快方法是什么,反之亦然?

3 个答案:

答案 0 :(得分:1)

尝试以下

    PixelColorRGBA[,] source = ...;
    byte[] dest = source
        .Cast<PixelColorRGBA>()
        .SelectMany(x => new byte[] { x.Blue, x.Green, x.Red, x.Alpha })
        .ToArray();

答案 1 :(得分:1)

我最终得到以下代码:

var source = new PixelColorRGBA[1000, 1000];
var destination = new byte[4000000];
{
    var start = DateTime.Now;
    unsafe
    {
        for (var q = 0; q < 100; q++)
            fixed (PixelColorRGBA* tmpSourcePtr = &source[0, 0])
            {
                var sourcePtr = (IntPtr) tmpSourcePtr;
                Marshal.Copy(sourcePtr, destination, 0, 4000000);
            }
    }
    Console.WriteLine("MS: " + DateTime.Now.Subtract(start).TotalMilliseconds);
}

我的电脑需要62毫秒。

答案 2 :(得分:0)

您可以使用

System.Buffer.BlockCopy(myArray, 0, byteArray, 0, length) 

System.Runtime.InteropServices.Marshal.Copy(myArray, 0, destPtr, length);