Why I cannot use extern functions in fixed statement?

59 Views Asked by At

I am learning how to use unmanaged code in C#, so I've tried making some console apps using it. I have an external library with a function called fillArray, it returns a char pointer. When I try to use it in fixed statement a get an error "The expression cannot be used in a 'fixed' statemen".

char[] array = new char[42];
        unsafe
        {
            char* a = FunctionsHolder.fillArray(array); // it works
            fixed (char* p = FunctionsHolder.fillArray(array)) // here i have an error
            {
               //a bunch of code
            }
        }
1

There are 1 best solutions below

2
On BEST ANSWER

The fixed statement pins a managed object so that you can have a pointer to it. A pointer returned from a DLLImport function is not a managed object (it might be a pointer into one, if it came from a pointer you passed in), so the .NET runtime has no idea how to pin it.

In your case the returned pointer is probably to the middle of array. Since you trusted p/invoke to pin and unpin it, by the time you get ahold of the return value, the array might already have moved and the return pointer is meaningless.

You will need to keep the array pinned throughout in order to make meaningful use of pointers. For example:

unsafe
{
  char* p;
  fixed (char* parray = &array[0]) // pins entire array
  {
    p = DllFunctions.findInArray(array, array.Length, sought);
    // safely use `p`
  }
  // must not use `p` because the array object it points to is no longer pinned
}