Serialize a class before sending with socket
Hi,
I have the following class:
Code:
[Serializable()]
class Class1
{
private int a;
private int b;
private int[] c;
public int Init ()
{
a = 5;
b = 6;
c = new int[3];
c[0] = 1;
return 0;
}
public byte[] Serialize()
{
BinaryFormatter bin = new BinaryFormatter();
MemoryStream mem = new MemoryStream();
bin.Serialize(mem, this);
return mem.GetBuffer();
}
}
The following code calls the Serialize method:
Code:
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Class1 c= new Class1();
c.Init ();
byte[] buffer = c.Serialize();
}
}
}
But buffer does not contains only the data but also information for the deserialize process. I do not need it.
How can I write a "non default" Serialize that will do the work ?
Can I avoid unsafe code for this purpose ?
The exact size of data that must be sent is 2x4 + 3x4 = 20 bytes;
Thanks.
Re: Serialize a class before sending with socket
If you want custom serialization, implement ISerializable interface.
Re: Serialize a class before sending with socket
Hi,
Do you have any sample code ?
Thanks.
Re: Serialize a class before sending with socket
The MSDN article on the ISerializable interface contains explanations and an implementation example.
Re: Serialize a class before sending with socket
I tried the following code to convert a struct to array of bytes:
Code:
struct PcToTgtIsAlive
{
int a;
int b;
int c;
public void Init()
{
a = 1;
b = 2;
c = 3;
}
}
class Program
{
static void Main(string[] args)
{
PcToTgtIsAlive p = new PcToTgtIsAlive();
p.Init();
int rc=Marshal.SizeOf (p);
IntPtr pnt = Marshal.AllocHGlobal(Marshal.SizeOf(p));
Marshal.StructureToPtr(p, pnt, false);
byte []dest=new byte[12];
Marshal.Copy(pnt, dest, 0, Marshal.SizeOf(p));
}
}
It works. Is there a problem using this code ?
Thanks.
Re: Serialize a class before sending with socket
I'd prefer using streams.
The BinaryReader and BinaryWriter classes "wrap" around a FileStream, and enable you to have much more control on what you're serializing/deserializing, and in what order.
Read this:
http://msdn.microsoft.com/en-us/library/36b93480.aspx
And after that get familiar with read/write methods of BinaryReader/BinaryWriter, respectively.
Re: Serialize a class before sending with socket
Hi,
This works great when you send/receive messages from other PCs running C#.
The serialize method inserts into the stream some bytes that are not part of the message itself. Those bytes are required for the deseriallize process.
But if I send message to a vxWorks or linux system, those extra bytes will cause problems.
Thanks.