Click to See Complete Forum and Search --> : Convert an array of bytes to a structure


jhammer
March 15th, 2005, 01:42 AM
How can I convert an array of bytes to a given structure in C#?
I have data sent to me in a socket (something like void*). I know the structure of the data. I may have strings in it (with variable length - I can't predict it).

What's my best solution?

efkefk
October 28th, 2006, 05:06 PM
I have the same problem.
May be you know the answer now ?

efkefk
October 28th, 2006, 05:51 PM
I found a solution here (with MemoryStream): http://www.codeguru.com/forum/showthread.php?t=318431&highlight=MemoryStream

But not really friendly because my arrays of bytes are complex.

A "CopyMemory" function (coming from the so close c++) would have been so nice !

MadHatter
October 28th, 2006, 07:21 PM
you can only marshal the struct if it only contains blittable members. otherwise you're going to have to hand copy the contents of your byte array into the members of your struct. since you have strings, good luck.

if you do a search on GCHandle in the forums here, I showed how to copy a struct to a byte array (the topic was on sending a struct over the network or something like that) in that thread.

efkefk
October 29th, 2006, 11:36 AM
Thank you for your answer.

I took already some time to do the job with "MemoryStream" and "BinaryReader", and it seems to work.

Anyway, I will have a look at "GCHandle".