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

前端 未结 5 2273
走了就别回头了
走了就别回头了 2021-02-12 23:14

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

相关标签:
5条回答
  • 2021-02-12 23:29

    Unsafe code in C# allows the use of pointers. In the context of the CLR, there is no unmanaged code in C#.

    0 讨论(0)
  • 2021-02-12 23:42

    Unsafe code runs inside the CLR while un-managed code runs outside the 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.

    0 讨论(0)
  • 2021-02-12 23:45

    managed code runs under supervision of the CLR (Common Language Runtime). This is responsible for things like memory management and garbage collection.

    So unmanaged simply runs outside of the context of the 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.

    0 讨论(0)
  • 2021-02-12 23:47

    Unsafe - Code that can be outside the verifiable subset of CIL

    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.)

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

    0 讨论(0)
  • 2021-02-12 23:48

    Here is what you can do inside of an unsafe context.

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

    0 讨论(0)
提交回复
热议问题