How do I read from a NetworkStream into a struct?

238 views
Skip to first unread message

John

unread,
Apr 17, 2002, 2:53:26 PM4/17/02
to
I have a struct:

struct msg
{
int length;
int tag;
}

I want to read in from a network stream, like so:

msg m;
networkStream.Read( (byte[])m, 0, 8);

But this doesn't compile: Can't convert m to byte[].

What's the right way to do this?

Thanks,
John

NETMaster

unread,
Apr 17, 2002, 3:01:57 PM4/17/02
to
Unfortunately, .NET has no raw serializers!

you could use "unsafe" and pointers,
or check this helper functions for conversion
structure <=> byte[]


// ====================================================================
using System.Runtime.InteropServices;

public static byte[] RawSerialize( object anything )
{
int rawsize = Marshal.SizeOf( anything );
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.StructureToPtr( anything, buffer, false );
byte[] rawdatas = new byte[ rawsize ];
Marshal.Copy( buffer, rawdatas, 0, rawsize );
Marshal.FreeHGlobal( buffer );
return rawdatas;
}

public static object RawDeserialize( byte[] rawdatas, Type anytype )
{
int rawsize = Marshal.SizeOf( anytype );
if( rawsize > rawdatas.Length )
return null;
IntPtr buffer = Marshal.AllocHGlobal( rawsize );
Marshal.Copy( rawdatas, 0, buffer, rawsize );
object retobj = Marshal.PtrToStructure( buffer, anytype );
Marshal.FreeHGlobal( buffer );
return retobj;
}


// sample usage:
[StructLayout(LayoutKind.Sequential, Pack=1, CharSet=CharSet.Ansi)]
struct YourStruct
{
public Int32 First;
public Int32 Second;
[MarshalAs( UnmanagedType.ByValTStr, SizeConst=16 )]
public String Text;
}

YourStruct st;
st.First = 11;
st.Second = 22;
st.Text = "Hello";
byte[] rd = RawSerialize( st );
// reverse:
YourStruct rst = (YourStruct) RawDeserialize( rd, typeof(YourStruct));

// ==================================================================

NOTE:
- endian depending
- alignment depending (Pack=)
- character-system depending (CharSet=)
- for complex structures (nested/with arrays), try to simplify them first.


--
NETMaster (Thomas Scheidegger)
http://www.cetus-links.org/oo_csharp.html


"John" <johnf...@hotmail.com> wrote in message news:d89364bd.02041...@posting.google.com...

Nicholas Paldino [.NET/C# MVP]

unread,
Apr 17, 2002, 3:02:01 PM4/17/02
to
John,

You have two ways of doing this. The first would be to use unsafe code
and cast the pointer to the byte array to a pointer of the structure type
(just like in C/C++). If unsafe code is not an option for you, then you
will have to perform the conversion yourself, taking the first four bytes of
the array, and converting it to an int, assigning it to the structure, and
so on, and so on.

Hope this helps.


--
- Nicholas Paldino [.NET MVP]
- nicholas...@exisconsulting.com

"John" <johnf...@hotmail.com> wrote in message
news:d89364bd.02041...@posting.google.com...

Reply all
Reply to author
Forward
0 new messages