简体   繁体   English

为什么char的存储大小似乎会改变?

[英]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. b的长度是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. mSize是12,而不是我预期的20。

MSDN says char storage is 2 bytes. MSDN说char存储为2个字节。 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. 因为您正在编组,并且默认情况下,一个char将被编组为ANSI char而不是Unicode char。 So "balloon" is 8 characters, which is 8 bytes when ANSI encoded, plus 4 bytes for your int, which is 12. 因此,“ balloon”是8个字符,ANSI编码时为8个字节,int则为4个字节,即12个字节。

If you want the size to be 20 for marshalling, change your StructLayout and set the ChatSet to Unicode: 如果您希望编组的大小为20,请更改StructLayout并将ChatSet设置为Unicode:

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

Now you will have your struct size as 20. 现在您的结构大小为20。

MSDN says char storage is 2 bytes. MSDN说char存储为2个字节。

That is true when we are talking about a CLR char, but not in the context of marshalling. 当我们谈论CLR字符时,这是正确的,但在编组上下文中却不是。

  • char is 2 bytes or 16-bit Unicode character (U +0000 to U +ffff) char是2个字节或16位Unicode字符(U +0000至U + ffff)
  • char [] is a pointer type char []是指针类型
  • int is 4 bytes int是4个字节

hence, about marshalling, I would pick vcsjones' answer. 因此,关于编组,我会选择vcsjones的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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