BlockCopy

  • Thread starter Thread starter Urs Wigger
  • Start date Start date
U

Urs Wigger

From a socket, I read some data into a bytes buffer.

byte[] bytes = new byte[1024];
int headSize = 8;
int nRead = sock.Receive(bytes, 0, headSize, SocketFlags.Peek);

Next I would like to 'mask' the received data with a struct 'HeaderT'

public struct HeaderT
{
int packetSize;
int type;
};

In C++ this could be done similar to this:
HeaderT *pHead = (HeaderT *)bytes;

In C#, this obviously does not work, so I tried with BlockCopy():

HeaderT header = new HeaderT();
System.Buffer.BlockCopy(bytes, 0, header , 0, headSize);

But then I get the following syntax error
Argument '3': cannot convert from 'HeaderT' to 'System.Array'.

So far I found no solution. Any help would be appreciated
Regards Urs
 
Urs,

You will have to pass an array of type HeaderT into the function, with
one element in it.

Hope this helps.
 
You will have to pass an array of type HeaderT into the function, with
one element in it.

I don't think BlockCopy works with UDTs, only with the primitive
types. So I'd do something like this instead

HeaderT header;
header.packetSize = BitConverter.ToInt32( bytes, 0 );
header.type = BitConverter.ToInt32( bytes, 4 );


Actually you can, in unsafe code. But you may not want to do that.



Mattias
 
Back
Top