CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Feb 2005
    Location
    Israel
    Posts
    1,475

    Convert an array of bytes to a structure

    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?

  2. #2
    Join Date
    Apr 2003
    Posts
    108

    Re: Convert an array of bytes to a structure

    I have the same problem.
    May be you know the answer now ?

  3. #3
    Join Date
    Apr 2003
    Posts
    108

    Re: Convert an array of bytes to a structure

    I found a solution here (with MemoryStream): http://www.codeguru.com/forum/showth...t=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 !

  4. #4
    Join Date
    Mar 2004
    Location
    33°11'18.10"N 96°45'20.28"W
    Posts
    1,808

    Re: Convert an array of bytes to a structure

    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.

  5. #5
    Join Date
    Apr 2003
    Posts
    108

    Re: Convert an array of bytes to a structure

    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".

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured