简体   繁体   English

如何编组托管代码中的Subset byte []数组?

[英]How do I Marshal out a Subset byte[] Array in Managed Code?

Consider the following method (used in a factory method): 考虑以下方法(在工厂方法中使用):

private Packet(byte[] rawBytes, int startIndex)
{
    m_packetId = BitConverter.ToUInt32(rawBytes, startIndex);
    m_dataLength = BitConverter.ToUInt16(rawBytes, startIndex + 4);
    if (this.Type != PacketType.Data)
        return;
    m_bytes = new byte[m_dataLength];
    rawBytes.CopyTo(m_bytes, startIndex + Packet.HeaderSize);
}

The last two lines of code strike me wasteful. 最后两行代码使我感到浪费。 Allocating more memory and populating it with values from memory seems silly. 分配更多的内存并用内存中的值填充它似乎很愚蠢。

With unmanaged code, something like this is possible: 使用非托管代码,可能会发生以下情况:

    m_bytes = (rawBytes + (startIndex + Packet.HeaderSize));

(I didn't run it through a compiler so syntax is probably off, but you can see it's just a matter of pointer manipulation.) (我没有通过编译器运行它,因此语法可能已关闭,但是您可以看到这只是指针操作的问题。)

I ran into a similar problem the other day when an API returned a byte[] array that was really a short[] array. 前几天,当API返回的byte []数组实际上是short []数组时,我遇到了类似的问题。

Are these types of array permutations just the cost of using managed code or is there a new school of thinking that I'm just missing? 这些类型的数组置换仅仅是使用托管代码的代价,还是我只是想念一种新的思路?

Thanks in advance. 提前致谢。

Have you considered restructuring so that maybe the copy is not necessary? 您是否考虑过重组,以便可能不需要复制?

First option: store a reference to rawBytes in m_bytes and store the offset that needs to be added to all accesses into this byte array. 第一种选择: rawBytes m_bytes的引用存储在m_bytes ,并将需要添加到该字节数组的所有访问中的偏移量存储。

Second option: make m_bytes a MemoryStream instead, constructed from the buffer, an offset and a length; 第二种选择:将m_bytesMemoryStream ,由缓冲区,偏移量和长度构成; this constructor also does not copy the byte buffer and just allows access to the specified sub-segment. 此构造函数也不复制字节缓冲区,而仅允许访问指定的子段。

Keep in mind though that the price of avoiding the copy operation is that the rawBytes and m_bytes (array or stream) will be aliases, so changes to one will change the other too. 请记住,避免复制操作的代价是rawBytesm_bytes (数组或流)将是别名,因此对一个的更改也会更改另一个。

是的,这在托管代码中成本更高,但是没有什么可以阻止您使此方法变得unsafe并进行所需的指针操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM