Reflection.Serialize Unexpected Results

I am very new to C# and the TinyCLR framework.

I’m trying to serialize a structure but when I view the results in the array, they are not what I was expecting. Any insight would be appreciated. Below is my basic code.

[System.Serializable]
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct UbloxTransmitHeaderStructure
{
	public byte sync_1;         // 0xB5
	public byte sync_2;         // 0x62
	public byte msgClass;       // message class
	public byte msgId;          // message id
	public ushort msgLength;        // message length (data only)
}

UbloxTransmitHeaderStructure headerStruct = new UbloxTransmitHeaderStructure
{
	sync_1 = 0x01,
	sync_2 = 0x02,
	msgClass = 0x03,
	msgId = 0x04,
	msgLength = 5 // or set as needed
};

byte[] testBuffer = Reflection.Serialize(headerStruct, typeof(UbloxTransmitHeaderStructure));

Debug.WriteLine(Encoding.UTF8.GetString(testBuffer, 0, 10));

I’m expecting 1,2,3,4,5,0,0,0,0,0 in the testBuffer, however, the results in testBuffer are 169,239,44,102,0,64,128,193,0,1,64

Thank you.

I do not think the serialized data will map 1to1 like you are showing. I would not worry about the array content. Would bring the data back into an object gives the right results.

This is a display problem. Loop through the testBuffer, toString each byte and display them. UTF8 encoding isn’t going to produce the char “1” for the byte 0x01.

Thank you for the quick reply.

Gus - The idea is to move the data byte by byte from the structure to the array and then send the data from the array out the serial port. I do this with structures and unions in C but it appears unions aren’t a thing in C#. With that said, I am worried about what’s in the array because that is what will be sent out the serial port. Maybe there’s a better way of going about this but I haven’t found it yet.

Mr. John - I actually not looking at the displayed results…I set a break point and am looking at the actual testBuffer contents if that makes sense.

If the other side is not TinyCLR then maybe manually compact the byte array to fit your C union.

Keep it simple…

You are building a command to send to a GPS module.

Create a byte array and directly set each byte. Make sure you get the right byte order for the short.

Thank you for the replies.

It looks like I’ll have to pack the array directly…While doable, this is very tedious as I’ll have to manually pack multiple messages for for multiple peripherials. I guess I thought there’d be a C# equivalent to a Struct/Union in C.

Again, thank you for your help!!