如何在 C# 中使用不安全代码(使用指针的代码)
在C#中很少需要使用指针,但仍有一些需要使用的情况。例如,在下列情况中使用允许采用指针的不
安全上下文是正确的:
处理磁盘上的现有结构
涉及内部包含指针的结构的高级COM或平台调用方案
性能关键代码
不鼓励在其他情况下使用不安全上下文。具体地说,不应该使用不安全上下文尝试在C#中编写C代码。
警告使用不安全上下文编写的代码无法被验证为安全的,因此只有在代码完全受信任时才会执行该代码 。
换句话说,不可以在不受信任的环境中执行不安全代码。例如,不能从Internet上直接运行不安全代码。
该教程包括下列示例:
示例1使用指针复制一个字节数组。
示例2显示如何调用WindowsReadFile函数。
示例3显示如何打印可执行文件的Win32版本。
示例1
以下示例使用指针将一个字节数组从src复制到dst。用/unsafe选项编译此示例。
//fastcopy.cs
//compilewith:/unsafe
usingSystem;
classTest
{
// Theunsafekeywordallowspointerstobeusedwithinthe
// followingmethod:
staticunsafevoidCopy(byte[]src,intsrcIndex,
byte[]dst,intdstIndex,intcount)
{
if(src==null||srcIndex<0||
dst==null||dstIndex<0||count<0)
{
thrownewArgumentException();
}
intsrcLen=src.Length;
intdstLen=dst.Length;
if(srcLen-srcIndex<count||dstLen-dstIndex<count)
{
thrownewArgumentException();
}
//Thefollowingfixedstatementpinsthelocationof
thesrcanddst
//objectsinmemorysothattheywill
//notbemovedbygarbagecollection.
fixed(byte*pSrc=src,pDst=dst)
第 1 页