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

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

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

5条回答
  •  眼角桃花
    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.

提交回复
热议问题