1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Runtime.InteropServices; 6 using System.Text; 7 using System.Threading.Tasks; 8 9 namespace UnsafeTest 10 { 11 class Program 12 { 13 14 unsafe static void Main(string[] args) 15 { 16 #region 类调用方法1 17 CaryData cd = new CaryData(); 18 Console.WriteLine("改变前: {0}", cd.data); 19 20 fixed (int* p = &cd.data) 21 { 22 ChangeValue(p); 23 } 24 Console.WriteLine("改变后: {0}", cd.data); 25 26 Point pt = new Point(); 27 pt.x = 5; 28 pt.y = 6; 29 // Pin pt in place: 30 fixed (int* p = &pt.x) 31 { 32 SquarePtrParam(p); 33 } 34 Console.WriteLine("{0} {1}", pt.x, pt.y); 35 Console.ReadLine(); 36 #endregion 37 38 #region 托管传递非托管 39 string s11 = "Hello "; 40 string s22 = s11; 41 IntPtr p1 = Marshal.StringToHGlobalAnsi(s11); 42 IntPtr p12 = Marshal.StringToHGlobalAnsi(s11); 43 IntPtr p11 = Marshal.StringToHGlobalAnsi(s22); 44 #endregion 45 46 47 unsafe 48 { 49 Console.Read(); 50 51 string str = "Hello World"; 52 string str1 = str; 53 #region 示例1 54 //fixed (char* pStr = str, pStr1 = str)//fixed可以在非托管中定义多个指针,指针离开{}之后就被销毁 55 //{ 56 // Console.WriteLine("{0:D}", (int)pStr);输出str的地址,指针pStr指向变量str的地址 57 // char* pStr2;//创建一个新指针 58 // pStr2 = pStr;//把新指针指向变量的地址 59 // Console.WriteLine("{0}", *pStr2);//输出新指针所指向的第一个地址存储内容 60 // for (int i = 0; i < str.Length; i++)//依次打印出指针所指向的地址存储的后续内容 61 // { 62 // Console.Write("{0}", *(++pStr2)); 63 // } 64 //} 65 #endregion 66 67 68 #region 示例2 69 fixed (char* pStr1 = str1) 70 { 71 Console.WriteLine("{0:x}", (int)pStr1); 72 } 73 str += "!!!"; 74 fixed (char* pStr = str) 75 { 76 Console.WriteLine("{0:x}", (int)pStr); 77 } 78 fixed (char* pStr1 = str1) 79 { 80 Console.WriteLine("{0:x}", (int)pStr1); 81 } 82 #endregion 83 84 } 85 Console.ReadLine(); 86 87 } 88 #region 类调用方法1 89 unsafe static void SquarePtrParam(int* p) 90 { 91 *p += *p; 92 } 93 unsafe static void ChangeValue(int* pInt) 94 { 95 *pInt = 23111111; 96 } 97 #endregion 98 } 99 100 101 #region 类调用方法1 102 class CaryData 103 { 104 public int data; 105 } 106 107 class Point 108 { 109 public int x, y; 110 } 111 #region 112 113 }