//Author:smilelance
//From:http://blog.csdn.net/smilelance
//转换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);
}
}
[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解决了这个问题。
如果有可能,建议不要用数组,全部都用基本类型。