zoukankan      html  css  js  c++  java
  • SizeOf与Structure与Managed Code

    中午刚刚提交给MS一个case,问题描述如下:
    (这是一个开源的EXCEL的代码,原来是用vb.net写的,我用C#改写了一遍。vb.net中使用的API:FilePut是没有这个问题的,我自己写的这个,就是不行。)

    下面的Marshal.SizeOf(vt)这行代码中,对于我下面给出的例子里面,我希望的size应该是2+2+1,而不是内存对齐后的6。我如何得到5这个值?

     private void FilePut(System.ValueType vt)

    {            

             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上来分享给大家。

  • 相关阅读:
    第一周、学习嵌入式
    centos7及xfce桌面环境安装,远程工具配置使用方法
    第一次作业
    2018下C语言基础课第1次作业
    第二次作业
    第一次作业
    第0次作业
    博客园第五次作业
    博客园第四次作业
    博客园第三次作业
  • 原文地址:https://www.cnblogs.com/juqiang/p/12474.html
Copyright © 2011-2022 走看看