Want to read the information from socket into a struct object directly instead of char buffer

A

Ashutosh

Hello,

I am a newbie in CSharp.

In C++ if we want to read from socket into the struct object we
directly type cast it as
recv(socketid,(char*),&struct_object,sizeof(struct object))


But C Sharp does not allow such thing.
How to obtain the same effect in CSharp?

Thanks in advance.
 
N

Nicholas Paldino [.NET/C# MVP]

Ashutosh,

You could do it in C#, but you have to do it a little differently. .NET
does not have a mechanism by which you can take the contents of a structure
in memory and then just commit it to a byte array (well, you could using
unsafe code, and only if the type is blittable, but that's not a solution in
all cases).

Your best bet would be to serialize the structure on the sending end
into a byte array and send that over the socket (of course, sending the
length beforehand so that your client on the other side knows how many bytes
to read). Then, on the other side, read the bytes into a byte array, and
then pass that array to a MemoryStream object. Once you have the
MemoryStream, you can deserialize the instance on the other side.

As I said before, if you have blittable types, you can use unsafe code
to get the bytes from memory and then send those (and then use unsafe code
on the other side to reconstruct the structure from the byte array).
 
?

=?ISO-8859-1?Q?Arne_Vajh=F8j?=

Ashutosh said:
In C++ if we want to read from socket into the struct object we
directly type cast it as
recv(socketid,(char*),&struct_object,sizeof(struct object))

But C Sharp does not allow such thing.
How to obtain the same effect in CSharp?

If you are also sending from a .NET app then you can
Serialize/Deserialize to the Stream connected to the Socket.

If you need it to be independent of .NET then read byte
array, wrap it a MemoryStream, wrap it in a BinaryReader
and fill your struct from that.

Arne
 
B

Ben Voigt [C++ MVP]

Ashutosh said:
Hello,

I am a newbie in CSharp.

In C++ if we want to read from socket into the struct object we
directly type cast it as
recv(socketid,(char*),&struct_object,sizeof(struct object))


But C Sharp does not allow such thing.
How to obtain the same effect in CSharp?

C# does not allow such things.

Since you are new to C#, but have experience with C++, take a good look at
C++/CLI. It lets you do the low-level data manipulation in C++, but make a
library easily called from other .NET languages (no p/invoke or any such
extra stuff needed, your C++ "ref class"es show up the same as C# classes)
 

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