方式一
通过Marshal实现结构体和字节数组之间的转换。
using System;
using System.Runtime.InteropServices;
namespace MarshalSample
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct Message
{
public ushort begin;
[MarshalAs(UnmanagedType.U1)]
public bool result;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
public byte[] detail;
public ushort end;
};
class Program
{
public static byte[] StructToBytes<T>(T obj)
{
int size = Marshal.SizeOf<T>();
byte[] bytes = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, ptr, false);
Marshal.Copy(ptr, bytes, 0, size);
Marshal.FreeHGlobal(ptr);
return bytes;
}
public static T BytesToStruct<T>(byte[] bytes)
{
int size = Marshal.SizeOf<T>();