One option is to simply use the C # pointer types - this requires the unsafe block (or the modifier for the method / class) and compilation with /unsafe :
[DllImport(...)] static extern int GetBuffer(byte* buffer, ref int maxSize);
A buffer can be allocated in several different ways. One could use a fixed heap array:
fixed (byte* buffer = new byte[4096]) { int maxSize = buffer.Length; GetBuffer(buffer, ref maxSize); }
Another is to use stackalloc , although this is only possible for small buffers:
byte* buffer = stackalloc byte[4096]; int maxSize = 4096; GetBuffer(buffer, ref maxSize);
This particular approach is almost identical to your C code in terms of performance and distribution patterns.
Another option is to use marshaling for heap arrays and completely avoid pointers.
[DllImport(...)] static extern int GetBuffer([Out] byte[] buffer, ref int maxSize); byte[] buffer = new byte[4096]; int maxSize = buffer.Length; GetBuffer(buffer, ref maxSize);
source share