Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with byte arrays in C#

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

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

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

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?

In C++, I could do the following:

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

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

like image 714
Matt Davis Avatar asked Jan 03 '09 16:01

Matt Davis


1 Answers

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.

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.

like image 175
Spodi Avatar answered Sep 20 '22 17:09

Spodi