/// <summary> /// Struct to byte arr 结构体转换成字节数组,用于通讯信息转换 /// </summary> /// <param name="_struct"></param> /// <returns></returns> static public byte[] getBytes(PROCESSINFO _struct) { int size = Marshal.SizeOf(_struct); byte[] arr = new byte[size]; IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(_struct, ptr, true); Marshal.Copy(ptr, arr, 0, size); // 需要释放临时非托管区内存 Marshal.FreeHGlobal(ptr); return(arr); }
/// <summary> /// Byte arr to struct version 1 字节数组转换成结构体,用于通讯信息转换 /// </summary> /// <param name="arr"></param> /// <returns></returns> static public PROCESSINFO fromBytes(byte[] arr) { PROCESSINFO _struct = new PROCESSINFO(); int size = Marshal.SizeOf(_struct); IntPtr ptr = Marshal.AllocHGlobal(size); Marshal.Copy(arr, 0, ptr, size); _struct = (PROCESSINFO)Marshal.PtrToStructure(ptr, _struct.GetType()); // 需要释放临时非托管区内存 Marshal.FreeHGlobal(ptr); return(_struct); }
/// <summary> /// Byte arr to struct arr version 2 字节数组转换成结构体,用于通讯信息转换 /// </summary> /// <param name="arr"></param> /// <param name="desArrNum"></param> /// <returns></returns> static public PROCESSINFO[] fromBytes(byte[] arr, int desArrNum) { PROCESSINFO[] _struct = new PROCESSINFO[desArrNum]; int size = Marshal.SizeOf(typeof(PROCESSINFO)) * desArrNum; IntPtr ptr = Marshal.AllocHGlobal(size); for (int i = 0; i < desArrNum; i++) { Marshal.Copy(arr, i * Marshal.SizeOf(typeof(PROCESSINFO)), ptr, Marshal.SizeOf(typeof(PROCESSINFO))); _struct[i] = (PROCESSINFO)Marshal.PtrToStructure(ptr, _struct[i].GetType()); } // 需要释放临时非托管区内存 Marshal.FreeHGlobal(ptr); return(_struct); }