简体   繁体   English

C#中的不安全代码和非托管代码有什么区别?

[英]What is difference between unsafe code and unmanaged code in C#?

C#中的不安全代码和非托管代码有什么区别?

managed code runs under supervision of the CLR (Common Language Runtime). 托管代码在CLR(公共语言运行时)的监督下运行。 This is responsible for things like memory management and garbage collection. 这对内存管理和垃圾收集等事情负责。

So unmanaged simply runs outside of the context of the CLR. 所以unmanaged只是在CLR的上下文之外运行。 unsafe is kind of "in between" managed and unmanaged. 不安全是一种“介于”管理和非管理之间。 unsafe still runs under the CLR, but it will let you access memory directly through pointers. 不安全仍在CLR下运行,但它可以让你直接通过指针访问内存。

Unsafe code in C# allows the use of pointers. C#中的不安全代码允许使用指针。 In the context of the CLR, there is no unmanaged code in C#. 在CLR的上下文中,C#中没有非托管代码。

Unsafe code runs inside the CLR while un-managed code runs outside the CLR. 不安全的代码在CLR内部运行,而非托管代码在CLR外部运行。

An example of unsafe code would be: 不安全代码的一个例子是:

unsafe class MyClass
{
    private int * intPtr;
}

You can use pointers anywhere in this class. 您可以在此类的任何位置使用指针。

An example of unmanaged code is: 非托管代码的一个示例是:

class MyClass
{
    [DllImport("someUnmanagedDll.dll")]
    static extern int UnManagedCodeMethod(string msg, string title);

    public static void Main() 
    {
        UnManagedCodeMethod("calling unmanaged code", "hi");
    }
}

It is not necessarily unmanaged code itself, but calling it. 它不一定是非托管代码本身,而是调用它。

Unsafe - Code that can be outside the verifiable subset of MSIL 不安全 - 可能在MSIL的可验证子集之外的代码

Unmanaged - Code that is not managed by the runtime and is thus not visible to the GC (for example a native compiled x86 function would be unmanaged.) Unmanaged - 不是由运行时管理的代码,因此对GC不可见(例如,本机编译的x86函数将不受管理。)

from: http://forums.devx.com/archive/index.php/t-15405.html 来自: http//forums.devx.com/archive/index.php/t-15405.html

Here is what you can do inside of an unsafe context. 以下是您在不安全的环境中可以做的事情。

http://msdn.microsoft.com/en-us/library/aa664769%28v=VS.71%29.aspx http://msdn.microsoft.com/en-us/library/aa664769%28v=VS.71%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM