C#编程(七十五)----------C#使用指针

原文链接: http://blog.csdn.net/shanyongxu/article/details/47321441

 

在C#中使用指针的语法

如果想在C#中使用指针,首先对项目进行过配置:

 

 

 

 

 

 

看到属性了吗?单击:

 

 

 

看到那个允许不安全代码了吗?选中

 

 

然后将有关指针,地址的操作放在unsafe语句块中.使用unsafe关键字是告诉编译器这里的代码是不安全的.

 

unsafe关键字的使用:

(1)放在函数前,修饰函数,说明在函数内部或函数的形参涉及到指针操作:

unsafe static void FastCopy(byte[] src, byte[] dst, int count)

{

    // Unsafe context: can use pointers here.

}

 

不安全上下文的方位从参数列表扩展到方法的结尾,因此指针作为函数的参数时需使用unsafe关键字.

 

(2)将有关指针的操作放在由unsafe声明的不安全块中

unsafe{

//unsafe context:can use pointers here

}

 

 

案例:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace Csharp中使用指针

{

    class Program

    {

        static void Main(string[] args)

        {

            int i = 1;

            unsafe

            {

                Increment(&i);

            }

            Console.WriteLine(i+"\n");

 

            //演示如何使用指针操作字符串

 

            string s = "Code Project is cool";

            Console.WriteLine("the original string : ");

            Console.WriteLine("{0}\n",s);

 

            char[] b = new char[100];

 

            //将指定书目的字符从此实例中的指定位置复制到Unicode字符数组的指定位置

            s.CopyTo(0, b, 0, 20);

 

 

 

            Console.WriteLine("the encode string : ");

 

            unsafe

            {

                fixed (char* p = b)

                {

                    NEncodeDecode(p); 

                }

            }

            for (int t = 0; t < 10; t++)

            {

                Console.WriteLine(b[t]);

            }

            Console.WriteLine("\n");

 

            Console.WriteLine("the decoded string : ");

 

            unsafe

            {

                fixed (char* p = b)

                {

                    NEncodeDecode(p); 

                }

            }

            for (int t = 0; t < 20; t++)

                Console.Write(b[t]);

            Console.WriteLine();

            Console.ReadKey();

        }

        unsafe public static void Increment(int* p)

        {

            *p = *p + 1;

        }

        /// <summary>

        /// 将一段字符串通过异或运算进行编码解码的操作.如果您将一段字符串送入这个

        /// 函数,这个字符串会被编码,如果将这一段已经编码的字符送入这个函数,

        /// 这段字符串就会

        /// 解码

        /// </summary>

        /// <param name="s"></param>

        unsafe public static void NEncodeDecode(char* s)

        {

            int w;

            for (int i = 0; i < 20; i++)

            {

                w = (int)*(s + i);

                w = w ^ 5;//按位异或

                *(s + i) = (char)w;

            }

        }

 

    }

}

 

 

 

其中用到了fixed,下面对其进行必要的介绍:

fixed语句只能出现在不安全的上下文中,C#编译器只允许fixed语句中分配指向托管变量的指针,无法修改在fixed语句中初始化的指针.

fixed语句禁止垃圾回收器重定位可移动的变量.当你在语句或函数之前使用fixed时,你是告诉.net平台的垃圾回收器,在这个语句或函数执行完毕前,不得回收其所占用的内存空间.

posted on 2017-03-29 11:35  Sun‘刺眼的博客  阅读(586)  评论(0编辑  收藏  举报

导航