C#通讯时字节流和结构体互转
//Author:smilelance
//From:
//转换C#代码:
using System.Runtime.InteropServices;
//结构体转换成字节流
public static byte[] StructToBytes<T>(T obj)
{
int size = Marshal.SizeOf(typeof(T));
IntPtr bufferPtr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(obj, bufferPtr, false);
byte[] bytes = new byte[size];
Marshal.Copy(bufferPtr, bytes, 0, size);
return bytes;
}
catch(Exception ex)
{
throw new Exception("Error in StructToBytes ! " + ex.Message);
}
finally
{
Marshal.FreeHGlobal(bufferPtr);
}
}
//字节流转换成结构体
public static T BytesToStruct<T>(byte[] bytes, int startIndex = 0)
{
if (bytes == null) return default(T);
if (bytes.Length <= 0) return default(T);
int objLength = Marshal.SizeOf(typeof(T));
IntPtr bufferPtr = Marshal.AllocHGlobal(objLength);
try//struct_bytes转换
{
Marshal.Copy(bytes, startIndex, bufferPtr, objLength);
return (T)Marshal.PtrToStructure(bufferPtr, typeof(T));
}
catch(Exception ex)
{
throw new Exception("Error in BytesToStruct ! " + ex.Message);
}
finally
{
Marshal.FreeHGlobal(bufferPtr);
}
sizeof结构体大小
}
[StructLayout(LayoutKind.Sequential, Pack=1)]  //变量在内存中的对齐⽅式,每个结构体都需要public struct LolMsgHeader
{
public ushort wMsgLen;
public byte    header_ver;
public ushort uAction;
//动作⾏为
public uint  dwUid; //⽤户ID
public uint  dwSeq; //包的序列号
public uint  dwPid; //当前服务ID
};
public struct LOLMoveMsg
{
[MarshalAs(UnmanagedType.SysUInt, SizeConst = LOLMsgConst.MASK_LEN)]
public WORD        mask;                  // 掩码
[MarshalAs(UnmanagedType.ByValArray, SizeConst = LOLMsgConst.NAME_LEN)]
public byte[] szName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = LOLMsgConst.NAME_LEN)]
public string targetName;//⽬的对象
public short x;
public short y;
public byte byReached;//到达⽬的地,未到达0,到达1
};
//注意,之前遇到过在ios真机上运⾏不起来的bug,在android真机和ios模拟器上都是OK的问题,后来把所有的ByValArray改成ByValTStr解决了这个问题。
如果有可能,建议不要⽤数组,全部都⽤基本类型。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。