简体   繁体   中英

Why does the storage size of a char seem to change?

If I do

char c = 'A';
byte[] b = BitConverter.GetBytes(c);

Length of b is 2.

However, if I have the following struct for interop purposes

[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct MyStruct
{
    int i;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
    char[] c;

    public int TheInt
    {
        get { return i; }
        set { i = value; }
    }

    public string TheString
    {
        get { return new string(c); }
        set { c = value.ToCharArray(); }
    }
}

then do

MyStruct m = new MyStruct();
m.TheInt = 10;
m.TheString = "Balloons";

int mSize = Marshal.SizeOf(m);

mSize is 12, not 20 as I expected.

MSDN says char storage is 2 bytes. The first example supports this.

Am I doing something wrong with my struct? Am I missing something?

Because you are are marshaling, and by default, a char will get marshalled to an ANSI char instead of a Unicode char. So "balloon" is 8 characters, which is 8 bytes when ANSI encoded, plus 4 bytes for your int, which is 12.

If you want the size to be 20 for marshalling, change your StructLayout and set the ChatSet to Unicode:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 1)]

Now you will have your struct size as 20.

MSDN says char storage is 2 bytes.

That is true when we are talking about a CLR char, but not in the context of marshalling.

  • char is 2 bytes or 16-bit Unicode character (U +0000 to U +ffff)
  • char [] is a pointer type
  • int is 4 bytes

hence, about marshalling, I would pick vcsjones' answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM