C Structure to C# structure using sockets

G

Guest

I want to pass a C structure from a windows server to the C# client using the
Sockets. Will there be requirements to cast the data types in the C# client?
 
G

Guest

Hi Raj,

Normally you should use marshal incoming data to a C# struct (or marshal it
field per field if that suits your program). You can map your C-style struct
to a C# struct using decoration.

Check the Marshal class for more details on marshalling the data (or struct).

HTH,
Tom T.

You will
 
G

Guest

Is it applicable for the data interchange over socket also? As my C++ server
uses sockets to communicate to the C# Client which is also using the sockets.
For example, lets say the C# client receives a buffer of data from its socket
port. Lets say it knows which structure it has received in the buffer. Now,
can the client directly assign the buffer to the structure variable and
expect the type conversions to occur automatically using the Marshall class?
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top