November 2002
Intermediate to advanced
560 pages
11h 16m
English
C# allows the user to use a limited version of “inline C” to write pointer-based code.
To safely use pointers in a garbage-collected (GC) environment, there needs to be a mechanism to prevent GC-tracked objects from being relocated by the garbage collector. The runtime environment allows objects to be pinned in place, then exposed in C# in a declarative manner using the fixed statement. The example in Listing B.1 uses an unsafe context to sum up the bytes in a byte array.
static unsafe int DoSum(byte[] byteBuffer)
{
int length = byteBuffer.Length;
int sum = 0;
fixed (byte* pBuffer = byteBuffer)
{
byte* pCurrent = pBuffer;
while (pCurrent < pBuffer + length)
{
sum += *pCurrent;
pCurrent++;
}
}
return sum;
}
|
The fixed ...
Read now
Unlock full access