Csharp 简明教程

C

当以 unsafe 修饰符标记时,C# 允许在代码块函数中使用指针变量。 unsafe code 或非托管代码是一个使用 pointer 变量的代码块。

C# allows using pointer variables in a function of code block when it is marked by the unsafe modifier. The unsafe code or the unmanaged code is a code block that uses a pointer variable.

Pointers

pointer 是一个变量,其值为另一个变量的地址,即内存位置的直接地址。与任何变量或常量类似,您必须先声明一个指针,才能用它存储任何变量地址。

A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location. similar to any variable or constant, you must declare a pointer before you can use it to store any variable address.

指针声明的一般形式为 −

The general form of a pointer declaration is −

type *var-name;

以下是有效的指针声明−

Following are valid pointer declarations −

int    *ip;    /* pointer to an integer */
double *dp;    /* pointer to a double */
float  *fp;    /* pointer to a float */
char   *ch     /* pointer to a character */

以下示例演示使用不安全修饰符在 C# 中使用指针−

The following example illustrates use of pointers in C#, using the unsafe modifier −

using System;

namespace UnsafeCodeApplication {
   class Program {
      static unsafe void Main(string[] args) {
         int var = 20;
         int* p = &var;

         Console.WriteLine("Data is: {0} ",  var);
         Console.WriteLine("Address is: {0}",  (int)p);
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,它将产生以下结果−

When the above code wass compiled and executed, it produces the following result −

Data is: 20
Address is: 99215364

除了将整个方法声明为不安全代码,您还可以将代码的一部分声明为不安全代码。以下部分中的示例演示了这一点。

Instead of declaring an entire method as unsafe, you can also declare a part of the code as unsafe. The example in the following section shows this.

Retrieving the Data Value Using a Pointer

您可以使用 ToString() 方法检索指针变量引用的位置处存储的数据。以下示例演示了这一点−

You can retrieve the data stored at the located referenced by the pointer variable, using the ToString() method. The following example demonstrates this −

using System;

namespace UnsafeCodeApplication {
   class Program {
      public static void Main() {
         unsafe {
            int var = 20;
            int* p = &var;

            Console.WriteLine("Data is: {0} " , var);
            Console.WriteLine("Data is: {0} " , p->ToString());
            Console.WriteLine("Address is: {0} " , (int)p);
         }
         Console.ReadKey();
      }
   }
}

编译并执行上述代码后,它将产生以下结果−

When the above code was compiled and executed, it produces the following result −

Data is: 20
Data is: 20
Address is: 77128984

Passing Pointers as Parameters to Methods

您可以将指针变量作为参数传递给方法。以下示例说明了这一点−

You can pass a pointer variable to a method as parameter. The following example illustrates this −

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

编译并执行上述代码后,将产生以下结果 −

When the above code is compiled and executed, it produces the following result −

Before Swap: var1: 10, var2: 20
After Swap: var1: 20, var2: 10

Accessing Array Elements Using a Pointer

在 C# 中,数组名称和指向与数组数据类型相同的数据类型的指针不是同一种变量类型。例如,int *p 和 int[] p,不是同一种类型。您可以对指针变量 p 进行递增,因为它不会固定在内存中,但数组地址在内存中是固定的,您无法对它进行递增。

In C#, an array name and a pointer to a data type same as the array data, are not the same variable type. For example, int *p and int[] p, are not same type. You can increment the pointer variable p because it is not fixed in memory but an array address is fixed in memory, and you can’t increment that.

因此,如果您需要使用指针变量访问数组数据,正如我们通常在 C 或 C++(请检查: C Pointers ) 中所做的那样,您需要使用 fixed 关键字修复指针。

Therefore, if you need to access an array data using a pointer variable, as we traditionally do in C, or C++ ( please check: C Pointers), you need to fix the pointer using the fixed keyword.

以下示例演示了这一点−

The following example demonstrates this −

using System;

namespace UnsafeCodeApplication {
   class TestPointer {
      public unsafe static void Main() {
         int[]  list = {10, 100, 200};
         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();
      }
   }
}

编译并执行上述代码后,它将产生以下结果−

When the above code was compiled and executed, it produces the following result −

Address of list[0] = 31627168
Value of list[0] = 10
Address of list[1] = 31627172
Value of list[1] = 100
Address of list[2] = 31627176
Value of list[2] = 200

Compiling Unsafe Code

要编译不安全代码,您必须使用命令行编译器指定 /unsafe 命令行开关。

For compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler.

例如,要从命令行编译包含不安全代码的名为 prog1.cs 的程序,请使用命令 −

For example, to compile a program named prog1.cs containing unsafe code, from command line, give the command −

csc /unsafe prog1.cs

如果您使用的是 Visual Studio IDE,那么您需要在项目属性中启用不安全代码的使用。

If you are using Visual Studio IDE then you need to enable use of unsafe code in the project properties.

为此−

To do this −

  1. Open project properties by double clicking the properties node in the Solution Explorer.

  2. Click on the Build tab.

  3. Select the option "Allow unsafe code".