[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);
}
}