日期:2014-05-17  浏览次数:21190 次

Marshal.SizeOf返回值不正确?
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace MarshalTest
{
    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct FileInfo_s
    {
        public Int32 mBlockNum; //4 Bytes

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] //32 Bytes
        public char[] mFileName;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 33)] //33 Bytes
        public char[] mMd5;
    };

    class Program
    {
        static void Main(string[] args)
        {
            FileInfo_s fileInfo = new FileInfo_s();
            Console.WriteLine(Marshal.SizeOf(fileInfo)); //72 ?
        }
    }
}

很奇怪为什么输出的是72个字节,而不是4+32+33 = 69个字节?
struct Marshal

------解决方案--------------------
内存对齐
http://bbs.csdn.net/topics/280068138
------解决方案--------------------
http://blog.csdn.net/wyqlxy/article/details/6608819