problem with the bytes sequence during marshalling in c

1 – Because your expected outcome is big endian, and your system appears to use little endian, so basically reversed order of bytes compared to what you expect.

2- Easiest way is to “convert” your numbers to big endian before marshalling (that is change them in a way which will produce desired result while converting them using little endian), for example like this:

 static int ToBigEndianInt(int x) {
    if (!BitConverter.IsLittleEndian)
        return x; // already fine
    var ar = BitConverter.GetBytes(x);
    Array.Reverse(ar);
    return BitConverter.ToInt32(ar, 0);
 }

static ushort ToBigEndianShort(ushort x) {
    if (!BitConverter.IsLittleEndian)
        return x; // already fine
    var ar = BitConverter.GetBytes(x);
    Array.Reverse(ar);
    return BitConverter.ToUInt16(ar, 0);
}

And then:

pack1.a = ToBigEndianInt(0x33333301);
pack1.b = ToBigEndianShort(200);

Note that this way of conversion is not very efficient and if you need more perfomance you can do this with some bit manipulations.

3 – Because string is null terminated, and this null terminator counts in SizeConst. Since you have it 5, there will be 4 characters of your string + 1 null terminator. Just increase SizeConst = 6 (that might add additional zeroes at the end because of Pack = 4).

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top