将结构转换为数组

来源:互联网 发布:货车配货软件 编辑:程序博客网 时间:2024/05/15 03:52
static byte[] StructToBytes(object structObj)
{
int size = Marshal.SizeOf(structObj);
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(structObj, buffer, false);
byte[] bytes = new byte[size];
Marshal.Copy(buffer, bytes, 0, size);
return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}

}

[Serializable]
public struct struct1
{
public int a;
public char b;
public int c;

};

unsafe void StructToBytes(object Astruct, byte[] buffer)
{
// MessageBox.Show(sizeof(struct1).ToString());
IntPtr p=new IntPtr();
System.Runtime.InteropServices.Marshal.StructureToPtr(Astruct, p, true);
byte* pb = (byte*)p;
for (int i = 0; i < sizeof(struct1); i++)
{
buffer[i] = *(pb++);
MessageBox.Show(Convert.ToString((*pb++)));
}
}

unsafe byte[] StructToBytes(byte *p,int len)
{
byte[] buffer = new byte[len];
for (int i = 0; i < sizeof(struct1); i++)
{
buffer[i] = *(p++);
// MessageBox.Show(Convert.ToString((*p++)));
}
return buffer;