简体   繁体   中英

What is the difference between Fixed and Unsafe

Why are there 2 different ways lock memory in place in .NET? What is the difference between them?

The fixed statement is used in the context of the unsafe modifier . Unsafe declares that you are going use pointer arithmetic(eg: low level API call), which is outside normal C# operations. The fixed statement is used to lock the memory in place so the garbage collector will not reallocate it while it is still in use. You can't use the fixed statement outside the context of unsafe.

Example

public static void PointyMethod(char[] array)
{
    unsafe
    {
        fixed (char *p = array)
        {
            for (int i=0; i<array.Length; i++)
            {
                System.Console.Write(*(p+i));
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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