Archived

This topic is now archived and is closed to further replies.

Trashcann

C# byte[] to struct packet

Recommended Posts

I need to send a struct
struct _packet
{
  public pType header;
  public byte[] data;
};
enum pType
{
  AwaitingRequest = 0,
  Transfer = 1,
  FileName = 2,
  FileSize = 3,
  BeginTransfer = 4,
  EndTransfer = 5,
  ReadyToRecieve = 6
};
 
to a socket, but the socket.Send() only accepts byte[]s. How do you suggest that I put this struct in an array of bytes? [edited by - Trashcann on April 3, 2004 5:50:47 PM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
You need to cast it:

(char *)&yourStructInstance

~Graham

Share this post


Link to post
Share on other sites
Whoops, forgot I''m not on my other machine, so the login information wasn''t saved.

~Graham

----
while (your_engine >= my_engine)
my_engine++;

Share this post


Link to post
Share on other sites
quote:
Original post by Anonymous Poster
You need to cast it:

(char *)&yourStructInstance

~Graham

C# is not C++.

Make a new byte array and put the values in manually.

P.S. Won''t you need to put the length of the data payload into the packet also?

Share this post


Link to post
Share on other sites
Manually assigning values works, but another method is as follows:

[StructLayout(LayoutKind.Sequential, Pack=1)]
struct YourClass {
// Whatever
}


GCHandle handle = GCHandle.Alloc(test, GCHandleType.Pinned);
try {
t = (Test2)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Test2));
}
finally {
handle.Free();
}

There''s a number of ways to accomplish this if this doesn''t do it for you, try gooling it.

Share this post


Link to post
Share on other sites
@antareus: no, since an int will take the first 2 bytes, all I have to do is take whats left of it... as for seeing how long it is, thats what .Length is for

@cavemanbob: Thanks, I''ll try that out.

Share this post


Link to post
Share on other sites
The only trouble with my method above is that you need to tell it how big the data bit is going to be. It''s probably just easier to make a constructor in the struct that takes the byte array and fills the header member and Array.Copy the rest of the data over.

Share this post


Link to post
Share on other sites
You could also use MemoryStream and write to the byte[] array like a stream. That way you can use stuff like WriteInt32()... (or whatever size type you want to use to send your enum)


[edited by - joanusdmentia on April 4, 2004 6:07:23 AM]

Share this post


Link to post
Share on other sites
Below is a link to Chris Taylors blog that shows a few different ways, including thier pros and cons, of converting a byte to a struct and a struct to a byte.

http://dotnetjunkies.com/WebLog/chris.taylor/archive/2004/03/13/9017.aspx

Hope it helps,
synth0id

Share this post


Link to post
Share on other sites