Game Development Reference
In-Depth Information
Using an Unsafe Context
C# code executes in either a safe or unsafe context. Safe is the default, but any use
of pointers requires that an unsafe context be used. The unsafe keyword is used to
denote an unsafe context. Unsafe code is still managed by the Common Language
Runtime, just like safe code, the only difference being that programmers can use
pointers to manipulate memory directly. Unsafe code runs outside of the auto-
matic memory management capabilities provided by the garbage collector, though
the Common Language Runtime is always aware of the code. The unsafe keyword
is an enhancement to make unsafe code a little bit safer. Code executing in an
unsafe context is not verified to be safe, so the code must be fully trusted in order
to execute the unsafe code. Unsafe code cannot be executed in an untrusted envi-
ronment like the Internet.
The unsafe keyword can be applied on methods, properties, constructors (exception
static), and extenders. Running code in an unsafe context is much more efficient
than using references because the garbage collector and an extra layer are bypassed
to decrease overhead. Unsafe code also increases performance by getting rid of
array bounds checking (though you are now responsible for it).
Aside from placing code within an unsafe construct, you must also configure the
compiler to allow unsafe code to be used. This can be done through the property
pages for the project or by using the /unsafe switch flag with csc.exe .
The following code shows how to properly use the unsafe keyword in a couple of
ways.
public void unsafe MyMethod(int* arg)
{
// Use arg parameter here
}
public void MyMethod(int arg)
{
unsafe
{
fixed (int* argPtr = arg)
{
// Use argPtr parameter here
}
}
}
Search Nedrilad ::




Custom Search