Search code examples
c#.net-corepinvoke

pinvoke: Threads vs shared memory buffer


After reading multiple post on SO, I need to pre-allocate my memory buffer on the C# side, pass it to the native side so when the function returns the value in the memory buffer will be properly filled (this avoid multiple copies of the data).

See:

Which does basically:

[DllImport("NativePlugin", CallingConvention = CallingConvention.Cdecl)]
private static extern void fillArrayNative(IntPtr data, int count, out int outValue);

public unsafe void getFillArrayNative(float[] outArray, int count, out int outValue)
{
    //Pin Memory
    fixed (float* p = outArray)
    {
        fillArrayNative((IntPtr)p, count, out outValue);
    }
}

How can I make sure this function will be thread-safe ? The point here is that the same buffer outArray should be used as I iterate over each files and populate the outArray.


Solution

  • How can I make sure this function will be thread-safe ?

    The same way you make sure every other function is threadsafe.

    While fillArrayNative is running it presumably have exclusive accesses to the array. If the method uses threads internally it is up to the method itself to perform any necessary synchronization.

    Once fillArrayNative returns it presumably does not access the array anymore. If it does save the pointer for later use you will have more than threading problems. After the fixed statement ends the array may be moved by the garbage collector, and accessing the pointer after that point will be unpredictable, but probably very bad.

    If you intend to to update the array at the same time you read it, then a simple array is simply not appropriate. Bu the question lack sufficient information to suggest the best approach for this scenario.