开发者

Copy 2d array of structs to byte[]

开发者 https://www.devze.com 2023-02-25 02:51 出处:网络
I have something like that: [StructLayout(LayoutKind.Explicit)] public struct PixelColorRGBA { [FieldOffse开发者_JS百科t(0)]

I have something like that:

[StructLayout(LayoutKind.Explicit)]
public struct PixelColorRGBA
{
    [FieldOffse开发者_JS百科t(0)]
    public UInt32 ColorBGRA;
    [FieldOffset(0)]
    public byte Blue;
    [FieldOffset(1)]
    public byte Green;
    [FieldOffset(2)]
    public byte Red;
    [FieldOffset(3)]
    public byte Alpha;
}

What is the fastest way to copy PixelColorRGBA[w, h] to byte[w * h * 4] and vise versa?


I end up with the following code:

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

It takes 62 ms on my computer.


Try the following

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


You can use

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

or

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

精彩评论

暂无评论...
验证码 换一张
取 消