使用字节数组在C#数组、字节

2023-09-04 01:05:55 作者:心掏给你玩╰玩腻了

我有一个字节数组重新presents一个完整的TCP / IP数据包。为了澄清,字节数组进行排序是这样的:

I have a byte array that represents a complete TCP/IP packet. For clarification, the byte array is ordered like this:

(IP包头 - 20字节)(TCP包头 - 20字节)(有效载荷 - X字节)

(IP Header - 20 bytes)(TCP Header - 20 bytes)(Payload - X bytes)

我有一个解析函数,它接受一个字节数组,并返回一个 TCPHeader 对象。它看起来是这样的:

I have a Parse function that accepts a byte array and returns a TCPHeader object. It looks like this:

TCPHeader Parse( byte[] buffer );

由于原始字节数组,这里有一种方法,我调用这个函数现在。

Given the original byte array, here is the way I'm calling this function right now.

byte[] tcpbuffer = new byte[ 20 ];
System.Buffer.BlockCopy( packet, 20, tcpbuffer, 0, 20 );
TCPHeader tcp = Parse( tcpbuffer );

有没有传递TCP字节数组的便捷方式,即字节的完整的TCP / IP包20-39,到解析功能,没有它解压到一个新的字节数组第一?

Is there a convenient way to pass the TCP byte array, i.e., bytes 20-39 of the complete TCP/IP packet, to the Parse function without extracting it to a new byte array first?

在C ++中,我能做到以下几点:

In C++, I could do the following:

TCPHeader tcp = Parse( &packet[ 20 ] );

这有什么用C#相似?我想避免临时字节数组,如果可能的话,创建和后续的垃圾回收

Is there anything similar in C#? I want to avoid the creation and subsequent garbage collection of the temporary byte array if possible.

推荐答案

您可以在.NET框架看到一种常见的做法,那我建议使用在这里,被指定偏移量和长度。因此,请您解析函数也接受了补偿传递的数组中,和要素的使用数量。

A common practice you can see in the .NET framework, and that I recommend using here, is specifying the offset and length. So make your Parse function also accept the offset in the passed array, and the number of elements to use.

当然,适用同样的规则,如果你要传递一个指针就像在C ++ - 数组不应该被修改,否则可能会导致未定义的行为,如果你不知道什么时候完全数据将被使用。但是,这是没有问题的,如果你不再会被修改阵列。

Of course, the same rules apply as if you were to pass a pointer like in C++ - the array shouldn't be modified or else it may result in undefined behavior if you are not sure when exactly the data will be used. But this is no problem if you are no longer going to be modifying the array.