如何将结构转换为无副本的字节数组? [英] How do I convert a struct to a byte array without a copy?

查看:188
本文介绍了如何将结构转换为无副本的字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[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?
}

如何获取数组 myTest 并将其转换为字节[]?由于我的对象很大,所以我不想复制数组(内存复制等)

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)

推荐答案

由于数组很大,这实际上是您可以执行所需操作的唯一方法:

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;

此代码非常有效,即使是在紧密的循环中, ComputeHash 的结果也将被收集到快速的Gen0集合中,而 myBigArray 将在Large对象堆,且未移动或收集. Buffer.BlockCopy 在运行时进行了高度优化,即使在固定目标并使用展开的指针副本的情况下,也可以提供您可能实现的最快副本.

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.

这篇关于如何将结构转换为无副本的字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆