Converting a C# struct to a byte[] array?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am using UDP for network transmission and I need to pass a struct from the client to the server. How can I convert a struct to a byte array, which is the only Type I can send through UDP

So, to be perfectly clear

struct bla

int x
int y


I need to send the struct above to a UDP Client and hence the struct above must be converted into a byte array so I can specify that byte array as a parameter to

UDPClient.Send(byte[] buffer, buffer size, socketFlags

I'm guessing this is REALLY simple, but I've spent hours upon hours looking for the solution :

Thanks much
Ro
 
struct blah
{
int x;
int y;
}

If that's really the struct you have, I think the easisest way would
be

byte[] buffer = new byte[8];
Buffer.BlockCopy(BitConverter.GetBytes(blahvar.x), 0, buffer, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(blahvar.y), 0, buffer, 4, 4);



Mattias
 
Back
Top