Search code examples
c#arraysfixedunsafe

inner working of 'fixed': working on memory location or object?


In managed/unmanaged array interoperability, I have a case of not having the usual

fixed (byte* data = new byte[length])
{
    // work with the array
}

but rather, I want to pin an array where I only get a reference, like this:

IntPtr dataPtr = camera.Image2d.GetDataBuffer();
fixed (byte* data = (byte *)dataPtr)
{
   // work with the array
}

1) From my understanding, the bottom code should also work, since 'fixed' will pin a memory location low level in the memory manager, and not care about any objects pointing to it? (Meaning, I do not have the "root"/a direct pointer - even though there probably is not any such concept.)

One additional question:

2) The requirement to use 'fixed' comes from the CLR memory manager running concurrently to any executed code, thus it could move arrays at any time?


Solution

  • 1) the second one does not seem proper as using the fixed keyword you are trying to pin the pointer, not the actual object. And IntPtr is not even (afaik) a managed pointer, rather an unmanaged one.

    2) fixed creates a pointer to the specified managed variable; and without pinning, GC may relocate the variable to another memory location, thus pointer will become useless.

    from msdn:

    The fixed statement sets a pointer to a managed variable and "pins" that variable during the execution of the statement. Without fixed, pointers to movable managed variables would be of little use since garbage collection could relocate the variables unpredictably. The C# compiler only lets you assign a pointer to a managed variable in a fixed statement.