internal unsafe struct Buffer
public fixed char fixedBuffer[128];
internal unsafe class Example
public Buffer buffer = default;
private static void AccessEmbeddedArray()
var example = new Example();
unsafe
// Pin the buffer to a fixed location in memory.
fixed (char* charPtr = example.buffer.fixedBuffer)
*charPtr = 'A';
// Access safely through the index:
char c = example.buffer.fixedBuffer[0];
Console.WriteLine(c);
// Modify through the index:
example.buffer.fixedBuffer[0] = 'B';
Console.WriteLine(example.buffer.fixedBuffer[0]);
static unsafe void Copy(byte[] source, int sourceOffset, byte[] target,
int targetOffset, int count)
// If either array is not instantiated, you cannot complete the copy.
if ((source == null) || (target == null))
throw new System.ArgumentException("source or target is null");
// If either offset, or the number of bytes to copy, is negative, you
// cannot complete the copy.
if ((sourceOffset < 0) || (targetOffset < 0) || (count < 0))
throw new System.ArgumentException("offset or bytes to copy is negative");
// If the number of bytes from the offset to the end of the array is
// less than the number of bytes you want to copy, you cannot complete
// the copy.
if ((source.Length - sourceOffset < count) ||
(target.Length - targetOffset < count))
throw new System.ArgumentException("offset to end of array is less than bytes to be copied");
// The following fixed statement pins the location of the source and
// target objects in memory so that they will not be moved by garbage
// collection.
fixed (byte* pSource = source, pTarget = target)
// Copy the specified number of bytes from source to target.
for (int i = 0; i < count; i++)
pTarget[targetOffset + i] = pSource[sourceOffset + i];