Consider a 2D, rectangular array. Say:
int[,] values = new int[len1, len2];
How can you iterate through all of its values in unsafe code?
The following works in an unsafe context.
fixed (int* baseOffset = values)
{
var offset = baseOffset;
var count = len1 * len2;
for (int i = 0; i < count; i++)
{
int value = *offset;
// Do whatever you need to do here
offset++;
}
}
Note that to get a pointer to the first item in an array, the types must match. So if you have a byte* which you want to treat as ushort*, you cannot cast the pointer within the fixed statement's parentheses, although you can do this within the block.