Search code examples
arraysc++-clipin-ptr

useless pin_ptr while copying array


I have some legacy code, which copy a native array into a managed one:

float* nativeValues = new float[NumberOfSamples];
array<double>^ managedValues = gcnew array<double>(NumberOfSamples);

pin_ptr<double> pinnedValues = &managedValues[0];
for (int i = 0; i < managedValues->Length; i++)
{
    nativeValues[i] = (float) pinnedValues[i];
}

I can't refactor it with Runtime::InteropServices::Marshal::Copy because the original array is double and the target one is float.

My problem is I don't get why the pin_ptr. I dont' think is needed but its a critical piece of code and I'd like to be sure before removing it.

Do you think is it safe to remove it?


Solution

  • The pin_ptr would be needed if you were going to pass the pin_ptr directly to an unmanaged API as a double*.

    void SomeUnmanagedAPI(double* data, int length);
    
    // Example of where pin_ptr would be needed.
    pin_ptr<double> pinnedValues = &managedValues[0];
    SomeUnmanagedAPI(pinnedValues, managedValues->Length);
    

    For either the manual copy, or the Marshal::Copy, it's not needed. Go ahead and remove it, and just iterate over managedValues.