亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C#中結(jié)構(gòu)體和字節(jié)數(shù)組轉(zhuǎn)換實(shí)現(xiàn)

 更新時(shí)間:2015年06月05日 10:17:29   投稿:junjie  
這篇文章主要介紹了C#中結(jié)構(gòu)體和字節(jié)數(shù)組轉(zhuǎn)換實(shí)現(xiàn),本文直接給出了字節(jié)數(shù)組與結(jié)構(gòu)體的轉(zhuǎn)換代碼,代碼中包含詳細(xì)注釋,需要的朋友可以參考下

最近在使用結(jié)構(gòu)體與字節(jié)數(shù)組轉(zhuǎn)化來實(shí)現(xiàn)socket間數(shù)據(jù)傳輸?,F(xiàn)在開始整理一下。對(duì)于Marshal可以查閱msdn,關(guān)于字節(jié)數(shù)組與結(jié)構(gòu)體轉(zhuǎn)代碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace FileSendClient
{
 
  [StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
  struct StructDemo
  {
    
    public byte a;
    public byte c;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
    public byte[] b;
    public byte d;
    public int e;
    
  }
  unsafe class Program
  {
    static void Main(string[] args)
    {
      StructDemo sd;
      sd.a = 0;
      sd.d = 0;
      sd.c = 0;
      sd.b = new byte[3] { 0, 0, 1 };
      sd.e = 5;
      int size = 0;
      //此處使用非安全代碼來獲取到StructDemo的值
      unsafe
      {
        size = Marshal.SizeOf(sd);
      }
       
      byte[] b = StructToBytes(sd,size);
 
      ByteToStruct(b, typeof(StructDemo));
 
    }
 
 
    //將Byte轉(zhuǎn)換為結(jié)構(gòu)體類型
    public static byte[] StructToBytes(object structObj,int size)
    {
      StructDemo sd;
      int num = 2;
      byte[] bytes = new byte[size];
      IntPtr structPtr = Marshal.AllocHGlobal(size);
      //將結(jié)構(gòu)體拷到分配好的內(nèi)存空間
      Marshal.StructureToPtr(structObj, structPtr, false);
      //從內(nèi)存空間拷貝到byte 數(shù)組
      Marshal.Copy(structPtr, bytes, 0, size);
      //釋放內(nèi)存空間
      Marshal.FreeHGlobal(structPtr);
      return bytes;
 
    }
 
    //將Byte轉(zhuǎn)換為結(jié)構(gòu)體類型
    public static object ByteToStruct(byte[] bytes, Type type)
    {
      int size = Marshal.SizeOf(type);
      if (size > bytes.Length)
      {
        return null;
      }
      //分配結(jié)構(gòu)體內(nèi)存空間
      IntPtr structPtr = Marshal.AllocHGlobal(size);
      //將byte數(shù)組拷貝到分配好的內(nèi)存空間
      Marshal.Copy(bytes, 0, structPtr, size);
      //將內(nèi)存空間轉(zhuǎn)換為目標(biāo)結(jié)構(gòu)體
      object obj = Marshal.PtrToStructure(structPtr, type);
      //釋放內(nèi)存空間
      Marshal.FreeHGlobal(structPtr);
      return obj;
    }
  }
}

相關(guān)文章

最新評(píng)論