码迷,mamicode.com
首页 > Windows程序 > 详细

C# 可否对内存进行直接的操作?

时间:2015-10-19 12:20:56      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:

可以,用 unsafe。用的时候记得在项目属性(Properties)->生成(Build)->常规(General)中钩上允许不安全代码 (Allow unsafe code)。
否则会出现这个错误:Unsafe code may only appear if compiling with /unsafe。
技术分享

技术分享

// compile with: /unsafe

using System;
class UnsafeTest
{
// Unsafe method: takes pointer to int:
unsafe static void SquarePtrParam(int* p)
{
*p *= *p;
}

unsafe static void Main()
{
int i = 5;
// Unsafe method: uses address-of operator (&):
SquarePtrParam(&i);
Console.WriteLine(i);
}
}
// Output: 25

技术分享
// compile with: /unsafe

using System;
class UnsafeTest
{
    // Unsafe method: takes pointer to int:
    unsafe static void SquarePtrParam(int* p)
    {
        *p *= *p;
    }

    unsafe static void Main()
    {
        int i = 5;
        // Unsafe method: uses address-of operator (&):
        SquarePtrParam(&i);
        Console.WriteLine(i);
    }
}
// Output: 25
技术分享
技术分享
技术分享
// compile with: /unsafe

using System;
class UnsafeTest
{
    // Unsafe method: takes pointer to int:
    unsafe static void SquarePtrParam(int* p)
    {
        *p *= *p;
    }

    unsafe static void Main()
    {
        int i = 5;
        // Unsafe method: uses address-of operator (&):
        SquarePtrParam(&i);
        Console.WriteLine(i);
    }
}
// Output: 25
技术分享

C# 可否对内存进行直接的操作?

标签:

原文地址:http://www.cnblogs.com/binyao/p/4891182.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!