Unsafe Code and Pointers
C# supports direct memory manipulation via pointers within blocks of code
marked unsafe and compiled with the /unsafe compiler option. Pointer types are
primarily useful for interoperability with C APIs, but may also
be used for accessing memory outside the managed heap or for
performance-critical hotspots.
Pointer Basics
For every value type or pointer type V, there is a corresponding pointer type V*. A pointer instance holds the address of a variable. Pointer types can be (unsafely) cast to any other pointer type. The main pointer operators are:
Operator | Meaning |
|---|---|
| The address-of operator returns a pointer to the address of a variable. |
| The dereference operator returns the variable at the address of a pointer. |
| The
pointer-to-member operator is a syntactic
shortcut, in which |
Unsafe Code
By marking a type, type member, or statement block with the
unsafe keyword, you’re permitted to
use pointer types and perform C++-style pointer operations on memory
within that scope. Here is an example of using pointers to quickly
process a bitmap:
unsafe void BlueFilter (int[,] bitmap)
{
int length = bitmap.Length;
fixed (int* b = bitmap)
{
int* p = b;
for (int i = 0; i < length; i++)
*p++ &= 0xFF;
}
}Unsafe code can run faster than a corresponding safe implementation. In this case, the code would have required a nested loop with array indexing and bounds checking. An unsafe C# method may also be faster than calling an external C function, since there ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access