程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#:結構體

C#:結構體

編輯:關於C語言

[StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]

public struct Data

{

public int MessageID;

public double price;

public long number;

[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 20)]

public string str;

//public char[] str;

/**

public Data(int i)

{

MessageID = 0;

price = 0.0;

number = 0;

str = new char[i];

}

* **/

}

http://rtx2005.blog.163.com/blog/static/85282552007112101729996/

public byte[] rawSerialize(object obj)
    {
      int rawsize = Marshal.SizeOf(obj);
      IntPtr buffer = Marshal.AllocHGlobal(rawsize);
      Marshal.StructureToPtr(obj, buffer, false);
      byte[] rawdatas = new byte[rawsize];
      Marshal.Copy(buffer, rawdatas, 0, rawsize);
      Marshal.FreeHGlobal(buffer);
      return rawdatas;
}

public BMTData rawDeserialize(byte[] rawdatas)
    {
      Type anytype = typeof(BMTData);
      int rawsize = Marshal.SizeOf(anytype);
      if (rawsize > rawdatas.Length)
        return new BMTData();
      IntPtr buffer = Marshal.AllocHGlobal(rawsize);
      Marshal.Copy(rawdatas, 0, buffer, rawsize);
      object retobj = Marshal.PtrToStructure(buffer, anytype);
      Marshal.FreeHGlobal(buffer);
      return (BMTData)retobj;
}

private void ReadStruct()
    {
      int currentLength = MemDB.GetLength();
      int currentCount = MemDB.GetCount();
      Byte[] data = new Byte[currentLength];
      MemDB.Read(ref data);
      BMTData item = rawDeserialize(data);
      String str = item.MessageID + "," + item.number + "," + item.price + "," + item.str;
      MessageBox.Show(str);
      lblUsedSize.Text = currentLength.ToString();
      lblCount.Text = currentCount.ToString();
      return;
}

private void btnTest_Click(object sender, EventArgs e)
    {
      MessageBox.Show(Marshal.SizeOf(typeof(BMTData)) + "");
       List<BMTData> datas = new List<BMTData>();
       BMTData item = new BMTData();
       item.MessageID = 1;
       item.number = 100;
       item.price = 1.2;
       item.str = "ABCD";

       datas.Add(item);
      /**
       String str = item.MessageID + "," + item.number + "," + item.price + ",";
       foreach(char ch in item.str)
        str += ch;
       str += "n";
      **/
       //lstData.Items.Add(str);
       byte[] bytData = rawSerialize(item);
       MemDB.Write(bytData,bytData.Length);

    }
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved