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

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
 
M

Mattias Sjögren

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top