/// <summary>
/// 结构体 值类型转byte数组
/// BitConverter
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="structObj"></param>
/// <returns></returns>
public static byte[] StructToBytes<T>(this T structObj) where T : struct
{
int size = System.Runtime.InteropServices.Marshal.SizeOf(structObj);
byte[] bytes = new byte[size];
Other IntPtr structPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
System.Runtime.InteropServices.Marshal.StructureToPtr(structObj, structPtr, true);
System.Runtime.InteropServices.Marshal.Copy(structPtr, bytes, 0, size);
System.Runtime.InteropServices.Marshal.FreeHGlobal(structPtr);
return bytes;
}
/// <summary>
/// byte数组转 结构体 值类型
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="bytes">
/// <returns></returns>
public static T BytesToStuct<t>(this byte[] bytes) where T : struct
{
int size = System.Runtime.InteropServices.Marshal.SizeOf(default(T));
if (size > bytes.Length)
{
return default(T);
}
IntPtr structPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(size);
System.Runtime.InteropServices.Marshal.Copy(bytes, 0, structPtr, size);
T obj = (T)System.Runtime.InteropServices.Marshal.PtrToStructure(structPtr, typeof(T));
System.Runtime.InteropServices.Marshal.FreeHGlobal(structPtr);
return obj;
}
</t>
/// <summary>
/// 把对象序列化并返回相应的字节
/// </summary>
/// <param name="pObj">需要序列化的对象</param>
/// <returns>byte[]</returns>
static public byte[] SerializeObject(this object pObj)
{
if (pObj == null)
return null;
System.IO.MemoryStream _memory = new System.IO.MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(_memory, pObj);
_memory.Position = 0;
byte[] read = new byte[_memory.Length];
_memory.Read(read, 0, read.Length);
_memory.Close();
return read;
}
Other /// <summary>
/// 把字节反序列化成相应的对象
/// </summary>
/// <param name="pBytes">字节流
/// <returns>object</returns>
static public T DeserializeObject<t>(this byte[] pBytes)
{
T _newOjb ;
if (pBytes == null || pBytes.Length < 1) return default(T);
System.IO.MemoryStream _memory = new System.IO.MemoryStream(pBytes);
_memory.Position = 0;
BinaryFormatter formatter = new BinaryFormatter();
_newOjb = (T)formatter.Deserialize(_memory);
_memory.Close();
return _newOjb;
}
</t>