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; }