SizeOf与Structure与Managed Code
(这是一个开源的EXCEL的代码,原来是用vb.net写的,我用C#改写了一遍。vb.net中使用的API:FilePut是没有这个问题的,我自己写的这个,就是不行。)
下面的Marshal.SizeOf(vt)这行代码中,对于我下面给出的例子里面,我希望的size应该是2+2+1,而不是内存对齐后的6。我如何得到5这个值?
{
int size = 0;
size = Marshal.SizeOf(vt);
IntPtr p = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(vt,p,true);
byte[] buf = new byte[size];
Marshal.Copy(p,buf,0,size);
fs.Write(buf,0,buf.Length);
}
//调用的代码:
l = aFormat[lIndex].Length;
cFORMAT_RECORD.opcode = 0x1e;
cFORMAT_RECORD.length = (short)(l+1);
cFORMAT_RECORD.FormatLength = (byte)(l);
FilePut(cFORMAT_RECORD);
// 结构示例
[StructLayoutAttribute(LayoutKind.Sequential, CharSet=CharSet.Auto)]
struct FORMAT_RECORD
{
public short opcode;// 0x1e
public short length;//1+len(format)
[MarshalAs(UnmanagedType.U1, SizeConst=1)]public byte FormatLength;//len(format)
}//followed by the Format-Picture
等MS给我回复后,我把结果post上来分享给大家。