using System; public unsafe class ByteBuffer { byte* p; int length; public ByteBuffer(byte* p, int length) { this.p = p; this.length = length; } public void ReadScatter(int[] indexes, byte[] buf) { indexes = (int[])indexes.Clone(); Array.Sort(indexes); if(indexes[0] < 0 || indexes[indexes.Length - 1] >= length) throw new IndexOutOfRangeException(); for(int i = 0; i < indexes.Length; i++) buf[i] = p[indexes[i]]; } } public class Test { static unsafe void Main() { byte[] buf = new byte[42]; fixed(byte* p = buf) { ByteBuffer bb = new ByteBuffer(p, buf.Length); UntrustedCode(bb); } } static void UntrustedCode(ByteBuffer bb) { byte[] buf = new byte[2]; bb.ReadScatter((int[])(object)new uint[] { 0, unchecked((uint)-4) }, buf); Console.WriteLine("the original array length was: " + buf[1]); } }