c#結(jié)構(gòu)體和字節(jié)流之間的相互轉(zhuǎn)換
結(jié)構(gòu)體轉(zhuǎn)byte數(shù)組
1 首先要明白 ,是 在那個(gè)命名空間下 System.Runtime.InteropServices;
2 首先得到結(jié)構(gòu)體的大小
2 開(kāi)辟相應(yīng)的內(nèi)存空間
3 將結(jié)構(gòu)體填充進(jìn)開(kāi)辟的內(nèi)存空間
4 從內(nèi)存空間拷貝進(jìn)byte數(shù)組
5 不要忘記釋放內(nèi)存哦
public static byte[] StructToBytes(object structObj, int size = 0)
{
if (size == 0)
{
size = Marshal.SizeOf(structObj); //得到結(jié)構(gòu)體大小
}
IntPtr buffer = Marshal.AllocHGlobal(size); //開(kāi)辟內(nèi)存空間
try
{
Marshal.StructureToPtr(structObj, buffer, false); //填充內(nèi)存空間
byte[] bytes = new byte[size];
Marshal.Copy(buffer, bytes, 0, size); //填充數(shù)組
return bytes;
}
catch (Exception ex)
{
Debug.LogError("struct to bytes error:" + ex);
return null;
}
finally
{
Marshal.FreeHGlobal(buffer); //釋放內(nèi)存
}
}
同理娄徊,接受到的byte數(shù)組喇颁,轉(zhuǎn)換為結(jié)構(gòu)體
1 開(kāi)辟內(nèi)存空間
2 用數(shù)組填充內(nèi)存空間
3 將內(nèi)存空間的內(nèi)容轉(zhuǎn)換為結(jié)構(gòu)體
4 同樣不要忘記釋放內(nèi)存
public static object BytesToStruct(byte[] bytes, Type strcutType, int nSize)
{
if (bytes == null)
{
Debug.LogError("null bytes!!!!!!!!!!!!!");
}
int size = Marshal.SizeOf(strcutType);
IntPtr buffer = Marshal.AllocHGlobal(nSize);
//Debug.LogError("Type: " + strcutType.ToString() + "---TypeSize:" + size + "----packetSize:" + nSize);
try
{
Marshal.Copy(bytes, 0, buffer, nSize);
return Marshal.PtrToStructure(buffer, strcutType);
}
catch (Exception ex)
{
Debug.LogError("Type: " + strcutType.ToString() + "---TypeSize:" + size + "----packetSize:" + nSize);
return null;
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}