Does MarshalAs result in an array copy?

Viewed 222

I have a project that handles considerably large arrays. Some of the code is written in C, and some of it is written in C#. To pass data from C to C#, I am using the MarshalAs attribute. Since the arrays are large, I would rather avoid copying. So my question is: Will MarshalAs cause the data to be copied from C to C#, or will the C# byte[] refer to the exact same location that was allocated by C?

A C function is responsible for passing the data to C#, which means I use a callback. The callback looks like this:

void (*to_call)(const uint8_t* buffer, int buffer_length);

DLLEXPORT
init(void(*callback)(const uint8_t* buffer, int buffer_length))
{
    to_call = callback;
}

Eventually, the to_call callback will be called from C. The C# code looks like this:

public delegate void Callback([In][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)]byte[] buffer, int bufferLength);

[DllImport(DLLPath)]
public static extern void init(Callback callback);

I would also like to know how the answer applies to .Net Framework and .Net Core.

1 Answers
Related