C#指针使用demo

#region 使用指针检索数据值
//class program
//{
//    // 1、项目属性勾选“允许不安全代码”
//    // 2、使用unsafe 修饰符
//    // 这里是将整个Main方法声明为不安全代码
//    //static unsafe void Main()
//    static void Main()
//    {
//        // 当代码段被 unsafe 修饰符标记时,C# 允许该代码段中的函数使用指针变量,
//        // 故使用了指针变量的代码块又被称为不安全代码或非托管代码。
//        int var = 20;

//        // 将部分代码声明为不安全代码
//        unsafe
//        {
//            int* p = &var;
//        }
//    }

//    public unsafe void swap(int* p, int* q)
//    {
//        int temp = *p;
//        *p = *q;
//        *q = temp;
//    }
//}
#endregion

#region 指针可以作为方法中的参数
// // using System;
// namespace UnsafeCodeApplication
// {
//     class TestPointer
//     {
//         public unsafe void swap(int* p, int* q)
//         {
//             int temp = *p;
//             *p = *q;
//             *q = temp;
//         }
//         public unsafe static void Main()
//         {
//             TestPointer p = new TestPointer();
//             int var1 = 10;
//             int var2 = 20;
//             int* x = &var1;
//             int* y = &var2;
//             Console.WriteLine("Before Swap: var1:{0}, var2: {1}", var1, var2);
//             p.swap(x, y);
//             Console.WriteLine("After Swap: var1:{0}, var2: {1}", var1, var2);
//             Console.ReadKey();
//         }
//     }
// }

#endregion

#region 使用指针访问数组元素  fixed()
namespace UnsafeCodeApplication
{
    //using System;
    class TestPointer
    {
        public unsafe static void Main()
        {
            int[] list = { 10, 100, 200 }; 

            // !!引用类型 都需要fixed,防止垃圾回收导致内存地址变化
            fixed (int* ptr = list)
            /* let us have array address in pointer */
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Address of list[{0}]={1}", i, (int)(ptr + i));
                Console.WriteLine("Value of list[{0}]={1}", i, *(ptr + i));
            }
            Console.ReadKey();
        }
    }
}
#endregion
原文地址:https://www.cnblogs.com/jshchg/p/11662163.html