BinaryFormatter, TYPE-SIZE Fine 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 BYTE type is 1 byte, the SHORT type is 2 bytes, and the INT type is 4 bytes, I expected a buffer with 7 bytes, but with the following code I got a buffer size of 232 bytes:

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 the IP address of the “exact buffer size” without crashing with code similar to the description:

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 structure. Is there any way?

+3
source share
1 answer

You can use interop and code as suggested by int this post . But keep in mind that the language is allowed to use any memory layout that it wants if you do not specify it, so you should use the attribute StructLayout.

, , .

, , , , - BinaryFormatter, XML JSON.

0

All Articles