How do I convert a struct to a byte array without a copy?

半腔热情 提交于 2020-01-15 05:45:08

问题


[StructLayout(LayoutKind.Explicit)]
public struct struct1
{
    [FieldOffset(0)]
        public byte a;   // 1 byte
    [FieldOffset(1)]
        public int b;    // 4 bytes
    [FieldOffset(5)]
        public short c;  // 2 bytes
    [FieldOffset(7)]
        public byte buffer;
    [FieldOffset(18)]
        public byte[] shaHashResult;   // 20 bytes
}

void DoStuff()
{
   struct1 myTest = new struct1();
   myTest.shaHashResult =  sha256.ComputeHash(pkBytes);  // 20 bytes

   byte[] newParameter = myTest.ToArray() //<-- How do I convert a struct 
                                          //     to array without a copy?
}

How do I take the array myTest and convert it to a byte[]? Since my objects will be large, I don't want to copy the array (memcopy, etc)


回答1:


Since you have a big array, this is really the only way you will be able to do what you want:

var myBigArray = new Byte[100000];

// ...

var offset = 0;
var hash = sha256.ComputeHash(pkBytes);
Buffer.BlockCopy(myBigArray, offset, hash, 0, hash.Length);

// if you are in a loop, do something like this
offset += hash.Length;

This code is very efficient, and even in a tight loop, the results of ComputeHash will be collected in a quick Gen0 collection, while myBigArray will be on the Large Object Heap, and not moved or collected. The Buffer.BlockCopy is highly optimized in the runtime, yielding the fastest copy you could probably achieve, even in the face of pinning the target, and using an unrolled pointer copy.



来源:https://stackoverflow.com/questions/13923360/how-do-i-convert-a-struct-to-a-byte-array-without-a-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!