ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-Unsafe(不安全代码)

 

1.A,示例(Sample) 返回顶部

“不安全代码”示例

本示例演示了如何在 C# 中使用非托管代码(使用指针的代码)。

安全说明

提供此代码示例是为了阐释一个概念,它并不代表最安全的编码实践,因此不应在应用程序或网站中使用此代码示例。对于因将此代码示例用于其他用途而出现的偶然或必然的损害,Microsoft 不承担任何责任。

在 Visual Studio 中生成并运行“不安全代码”示例

  1. 在“解决方案资源管理器”中,右击“FastCopy”项目并单击“设为启动项目”。

  2. 在“调试”菜单上,单击“开始执行(不调试)”。

  3. 在“解决方案资源管理器”中,右击“ReadFile”项目并单击“设为启动项目”。

  4. 在“解决方案资源管理器”中,右击“ReadFile”项目并单击“属性”。

  5. 打开“配置属性”文件夹并单击“调试”。

  6. 在“命令行参数”属性中,输入 ..\..\ReadFile.cs

  7. 单击“确定”。

  8. 在“调试”菜单上,单击“开始执行(不调试)”。

  9. 在“解决方案资源管理器”中,右击“PrintVersion”项目并单击“设为启动项目”。

  10. 在“调试”菜单上,单击“开始执行(不调试)”。

从命令行生成并运行“不安全代码”示例

  1. 使用“更改目录”命令转到“Unsafe”目录。

  2. 键入以下命令:

    cd FastCopy
    csc FastCopy.cs /unsafe
    FastCopy
  3. 键入以下命令:

    cd ..\ReadFile
    csc ReadFile.cs /unsafe
    ReadFile ReadFile.cs
  4. 键入以下命令:

    cd ..\PrintVersion
    csc PrintVersion.cs /unsafe
    PrintVersion

 

1.B,FastCopy 示例代码1(Sample Code)返回顶部

1.B.1, fastcopy.cs

// 版权所有(C) Microsoft Corporation。保留所有权利。
// 此代码的发布遵从
// Microsoft 公共许可(MS-PL,http://opensource.org/licenses/ms-pl.html)的条款。
//
//版权所有(C) Microsoft Corporation。保留所有权利。

// fastcopy.cs
// 编译时使用:/unsafe
using System;

class Test
{
    // unsafe 关键字允许在下列
    // 方法中使用指针:
    static unsafe void Copy(byte[] src, int srcIndex,
        byte[] dst, int dstIndex, int count)
    {
        if (src == null || srcIndex < 0 ||
            dst == null || dstIndex < 0 || count < 0)
        {
            throw new ArgumentException();
        }
        int srcLen = src.Length;
        int dstLen = dst.Length;
        if (srcLen - srcIndex < count ||
            dstLen - dstIndex < count)
        {
            throw new ArgumentException();
        }


        // 以下固定语句固定
        // src 对象和 dst 对象在内存中的位置,以使这两个对象
        // 不会被垃圾回收移动。
        fixed (byte* pSrc = src, pDst = dst)
        {
            byte* ps = pSrc;
            byte* pd = pDst;

            // 以 4 个字节的块为单位循环计数,一次复制
            // 一个整数(4 个字节):
            for (int n = 0; n < count / 4; n++)
            {
                *((int*)pd) = *((int*)ps);
                pd += 4;
                ps += 4;
            }

            // 移动未以 4 个字节的块移动的所有字节,
            // 从而完成复制:
            for (int n = 0; n < count % 4; n++)
            {
                *pd = *ps;
                pd++;
                ps++;
            }
        }
    }


    static void Main(string[] args)
    {
        byte[] a = new byte[100];
        byte[] b = new byte[100];
        for (int i = 0; i < 100; ++i)
            a[i] = (byte)i;
        Copy(a, 0, b, 0, 100);
        Console.WriteLine("The first 10 elements are:");
        for (int i = 0; i < 10; ++i)
            Console.Write(b[i] + " ");
        Console.WriteLine("\n");
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-08
  • 2021-06-20
  • 2021-04-09
  • 2021-08-18
  • 2021-06-15
  • 2021-09-25
猜你喜欢
  • 2022-12-23
  • 2021-09-16
  • 2022-12-23
  • 2021-09-25
相关资源
相似解决方案