public struct ItemInfo
    {
        public int ? postion;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
        public char[] id ;
        public int ? StartUnitPos;
        public int ? HaveUnit;
        public int ? ValueSize;
        public int ? PreValuePos;
        public int ? BackValuePos;
        public int ? flag;
        private int reserve;        public ItemInfo( int ? n  )
        {
            id = new char[512];
            postion = n ;
            StartUnitPos = n;
            HaveUnit = n;
            ValueSize = n;
            PreValuePos = n;
            BackValuePos = n;
            flag = n;
            reserve = 0;
        }
    }....protected ItemInfo ii = new ItemInfo(null);MessageBox.Show(string.Format("{0:d}", Marshal.SizeOf(ii)));以前没用[MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]时,得出数字是64,这是因为没有把数组占用空间算上。现在我指定了数组元素个数,可得出结果是572!不对啊!C# char是unicode字符,一个占两个字节,按理说应是1084啊!晕。晕。请高手指点!

解决方案 »

  1.   

    有了新的认识:MarshalAs是用来指定非托管类型的,char在非托管类型中长度就是一个字节。如何让C#知道我用的是宽字符呢 ?
      

  2.   

    不行就用int[] id;
    不过用时如何把int[] id ;转换为char[] id ; ?
      

  3.   

    [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]Unicode 以 Unicode 2 字节字符形式封送字符串。 
      

  4.   

    如下:    [Serializable]
        [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
        public struct ItemInfo
        {
            public int postion;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
            public char[] id;
            public int StartUnitPos;
            public int HaveUnit;
            public int ValueSize;
            public int PreValuePos;
            public int BackValuePos;
            public int flag;
            private int reserve;         public ItemInfo(int n)
            {
                postion = n ;
                id = new char[512];
                StartUnitPos = n;
                HaveUnit = n;
                ValueSize = n;
                PreValuePos = n;
                BackValuePos = n;
                flag = n;
                reserve = 0; 
            }
        }
      

  5.   

    哇咔咔!用Fred_Mark 方法搞定!感谢各位回贴,特别感谢Fred_Mark !以后还请大家多多关照!分不多,小弟在此诚心谢了!