Hi Raj,
I think it is applicable (I have little experience with programming sockets
though).
Marshal will convert the types it can map to C# equivalents. Suppose you
send a C-structs like the following:
struct DS
{
unsigned int ID;
unsigned int Data[ 127 ];
};
In C# you would map it as follows:
public struct DS
{
public uint ID;
[ MarshalAs( UnmanagedType.ByValArray,
ArraySubType = UnmanagedType.U4,
SizeConst = 127 ) ]
public uint[] Data;
}
IIRC, receiving from a socket returns a byte array. Marshal.PtrToStructure
needs an IntPtr though. Example:
byte[] data = new byte[ 512 ];
// <-- suppose data is filled from Socket.Receive here
GCHandle hData = GCHandle.Alloc( data, GCHandleType.Pinned );
try
{
DS ds = (DS) Marshal.PtrToStructure( hData.AddrOfPinnedObject(),
typeof(DS) );
// ds is now a regular C# struct instance
}
finally
{
hData.Free();
}
I agree that it doesn't seem very elegant, but it is the only way I know how
to do that.
HTH,
Tom T