C# 允许在代码块的函数中使用指针变量来标记不安全的修饰符。不安全代码或非托管代码是使用指针变量的代码块。
指针
指针是一个变量,其值是另一个变量的地址,即存储器位置的直接地址。 类似于任何变量或常量,要使用指针必须先声明指针,然后才能使用它来存储任何变量地址。
指针声明的一般形式是:
type *var-name
以下是有效的指针声明:
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# 中使用指针,使用不安全的修饰符:
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()
}
}
}
当上述代码通过编译并执行后,会产生以下结果:
Data is: 20
Address is: 890153869
不必将整个方法声明为不安全,也可将代码的一部分声明为不安全。下一节中的示例显示了这一点。
使用指针检索数据值
可以使用ToString()
方法检索由指针变量引用的位置处存储的数据。以下示例演示如下:
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()
}
}
}
当编译和执行上述代码时,会产生以下结果:
Data is: 20
Data is: 20
Address is: 97122341
将指针作为参数传递给方法
可以将指针变量传递给方法作为参数。以下示例说明了这一点:
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()
}
}
}
当上述代码被编译并执行时,它产生以下结果:
Before Swap: var1: 10, var2: 20
After Swap: var1: 20, var2: 10
使用指针访问数组元素
在 C# 中,一个数组名称和一个与数组数据类型相同的数据类型的指针是不一样的变量类型。 例如,int * p
和int [] p
是两个不一样的类型。我们可以增加指针变量p
,因为它在内存中不是固定的,而数组的地址是固定在内存中,所以不能增加。
因此,如果您需要使用指针变量来访问数组数据,如传统上在C语言或C++(请查阅:C指针)中所做的那样,则需要使用fixed
关键字修复指针。
以下示例演示如下:
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()
}
}
}
当编译和执行上述代码时,会产生以下结果:
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
编译不安全的代码
要编译不安全的代码,必须使用命令行编译器指定/unsafe
命令行开关。
例如,要编译一个名称为prog1.cs
的源代码中包含不安全代码,请从命令行中输入命令:
csc /unsafe prog1.cs
如果您使用的是Visual Studio IDE,则需要在项目属性中启用不安全的代码。
参考以下步骤:
- 通过双击解决方案资源管理器中的属性节点打开项目属性(project properties)。
- 单击构建(Build)选项卡。
- 选择“允许不安全代码(Allow unsafe code)”选项。