I found a - apparently - a more elegant and for some reason also faster way to do this:
byte[] rawData = new byte[1024]; GCHandle rawDataHandle = GCHandle.Alloc(rawData, GCHandleType.Pinned); int* iPtr = (int*)rawDataHandle.AddrOfPinnedObject().ToPointer(); int length = rawData.Length / sizeof (int); for (int idx = 0; idx < length; idx++, iPtr++) { (*iPtr) = idx; Console.WriteLine("Value of integer at pointer position: {0}", (*iPtr)); } rawDataHandle.Free();
Thus, the only thing I need to do - besides setting the correct iteration length - is to increase the pointer. I compared the code to the one that uses the fixed operator, and this one is a bit faster.
source share