C#笔记:使用Unsafe代码与结构体

  • 2019 年 11 月 22 日
  • 笔记

首先打开:属性-生成-允许不安全代码开关。

开始编码:

unsafe private void DoAction_Click(object sender, RoutedEventArgs e)  {      Node* list = CreateLinkList(new int[] { 1, 2, 3, 4 });        while(list->next!=null)      {          this.result.Content += (list->data).ToString() + "##";          list = list->next;      }  }    unsafe private Node* CreateLinkList(int[] inputList)  {      int length = inputList.Length;        Node* root = null;      root = CreateNode(0, "root 分配内存失败!");      root->next = null;        Node* listTail = root;//定义一个位置指针,指向链表尾        fixed (int* pIntStart = inputList) //操作一个托管对象要先fix一下。找到地址。      {          int* pInt = pIntStart;//引用一个临时指针用来指向传入的inputList            //开始循环创建链表          for (int i = 0; i < length; i++)          {              if(pInt==null)              {                  throw new Exception("粗大事了!!!未知错误使传入数组为null");              }                Node* temp = CreateNode(*pInt, "节点 分配内存失败");              temp->next = null;                //把新增节点加入到前一个节点              listTail->next = temp;                listTail = listTail->next;//把位置指针指向下一个节点              pInt++;//指向数组的指针往后指一位          }      }      return root;  }    unsafe private Node* CreateNode(int data, string errMsg)  {      Node* temp = null;      temp = (Node*)Marshal.AllocHGlobal(sizeof(Node));//尝试分配节点内存      if (temp == null)      {          throw new NullReferenceException(errMsg);      }        temp->data = data;        return temp;  }      unsafe struct Node  {      public int data;      public Node* next;  }