您的位置:首页 > 编程语言 > C#

[C#]结构体和字节数组的相互转化

2017-09-01 09:47 330 查看
public static class StructCopyer
{
//        相当于序列化与反序列化,但是不用借助外部文件
//1、struct转换为Byte[]
public static Byte[] StructToBytes(Object structure)
{
Int32 size = Marshal.SizeOf(structure);
IntPtr buffer = Marshal.AllocHGlobal(size);

try
{
Marshal.StructureToPtr(structure, buffer, false);
Byte[] bytes = new Byte[size];
Marshal.Copy(buffer, bytes, 0, size);

return bytes;
}
finally
{
Marshal.FreeHGlobal(buffer);
}

}

//2、Byte[]转换为struct
public static Object BytesToStruct(Byte[] bytes, Type strcutType)
{
Int32 size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(size);

try
{
Marshal.Copy(bytes, 0, buffer, size);

return Marshal.PtrToStructure(buffer, strcutType);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: