在c#中使用指针

   如果想在c#中使用指针,首先对项目进行配置:在解决方案资源管理器中右击项目名选择属性(或在项目菜单中选择consoleApplication属性(consoleApplication为项名)),在生成选项卡中 选中“允许不安全代码”,如下图:

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

unsafe关键字的使用:

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

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

{

    // Unsafe context: can use pointers here.

}

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

         unsafe static void FastCopy ( byte* ps, byte* pd, int count ) {...}

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

       unsafe

      {   

         // Unsafe context: can use pointers here. 

      }

 

示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{  
    class Program
    {

        
        static void Main(string[] args)
        {

            int i = 1;
            unsafe 
            { 
                Increment(&i); //将函数调用放在unsafe中是因为实参是指针类型
            }
            
            Console.WriteLine(i+"\n");

            //演示如何使用指针来操作字符串
            string s = "Code Project is cool";
            Console.Write("the original string : ");
            Console.WriteLine("{0}\n", s);

            char[] b = new char[100];
            s.CopyTo(0, b, 0, 20);//public void CopyTo (int sourceIndex,char[] destination,int destinationIndex,int count)
            //将指定数目的字符从此实例中的指定位置复制到 Unicode 字符数组中的指定位置。

            Console.Write("the encoded string : ");

            unsafe 
            {
                fixed (char* p = b) 
                { 
                    NEncodeDecode(p); 
                }
            }
            for (int t = 0; t < 20; t++)
                Console.Write(b[t]);
            Console.WriteLine("\n");

            Console.Write("the decoded string : ");
            unsafe
            { 
                fixed (char* p = b) 
                { 
                    NEncodeDecode(p); 
                } 
            }
            for (int t = 0; t < 20; t++)
                Console.Write(b[t]);
            Console.WriteLine();

        }


        unsafe public static void Increment(int* p)
        {

            *p = *p + 1;
        }

        unsafe public static void NEncodeDecode(char* s)
        {//将一段字符串通过异或运算进行编码解码的操作。如果您将一段字符串送入这个函数这个字符串将会被编码,
        //如果您将一段已经编码的字符送入这个函数,这段字符串将会被解码。
            int w;
            for (int y = 0; y < 20; y++)
            {
                w = (int)*(s + y);
                w = w ^ 5;//^为按位异或。
                *(s + y) = (char)w;
            }

        }
    }
}


输出结果:

 

关键字fixed简介:

   fixed语句只能出现在不安全的上下文中。

   C# 编译器只允许在 fixed 语句中分配指向托管变量的指针,无法修改在 fixed 语句中初始化的指针

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

 示例:

(1)

// assume class Point { public int x, y; }  pt is a managed variable, subject to garbage collection.

Point pt = new Point();

// Using fixed allows the address of pt members to be taken, and "pins" pt so it isn't relocated.(pin  v 固定住)

fixed ( int* p = &pt.x )

{

    *p = 1;

}

(2)用数组或字符串的地址初始化指针:

          fixed (int* p = arr) ...  // equivalent to p = &arr[0]

          fixed (char* p = str) ... // equivalent to p = &str[0]

(3)只要指针的类型相同,就可以初始化多个指针:

        fixed (byte* ps = srcarray,pd = dstarray) {...}

      要初始化不同类型的指针,只需嵌套 fixed 语句:

                fixed (int* p1 = &p.x)

   {

      fixed (double* p2 = &array[5])

    {       

      // Do something with p1 and p2.

   }

  }

 

 

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值