BinaryFormatter , exact TYPE-SIZE buffer
I have this serializable class :
[Serializable]
public class myClass
{
public byte myByte { get; set; }
public short myShort { get; set; }
public int myInt { get; set; }
}
开发者_高级运维knowing that the type BYTE is 1 byte and the type SHORT is 2 bytes and the type INT is 4 bytes, i was waiting for a 7 bytes buffer but with the following code I got a buffer size of 232 byte:
myClass mc = new myClass { myByte = 0xff, myShort = 0x009c, myInt = 0x00000045 };
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, mc);
byte[] buffer = ms.ToArray();
I would like to send over IP the 'exact type-sized buffer' without hassling with a code like the follwing :
byte[] exactBuffer = new byte[sizeof(byte) + sizeof(short) + sizeof(int)];
exactBuffer[0] = mc.myByte;
byte[] bmyShort = BitConverter.GetBytes(mc.myShort);
System.Buffer.BlockCopy(bmyShort, 0, exactBuffer, sizeof(byte), bmyShort.Length);
byte[] bmyInt = BitConverter.GetBytes(mc.myInt);
System.Buffer.BlockCopy(bmyInt, 0, exactBuffer, sizeof(byte)+sizeof(short), bmyInt.Length);
and I need the class to be a class not a struct. Is there any way ?
You could use interop and code like suggested int this post. But be aware that the language is allowed to use any memory layout it wishes, if you don't specify it, so you should use the StructLayout
attribute.
Also, if your class contained any references to other classes, this wouldn't work.
In general, transferring data like this over network tends not to be the solution and you should use something like BinaryFormatter
, XML or JSON.
精彩评论