Pointers and Arrays in C# - The fixed Statement
(Page 2 of 4 )
The fixed statement is required to pin a managed object, such as the bitmap in the previous example. During the execution of a program, many objects are allocated and deallocated from the heap. In order to avoid unnecessary waste or fragmentation of memory, the garbage collector moves objects around. Pointing to an object is futile if its address could change while referencing it, so the fixed statement tells the garbage collector to “pin” the object and not move it around. This may have an impact on the efficiency of the runtime, so fixed blocks should be used only briefly, and heap allocation should be avoided within the fixed block.
Within afixedstatement, you can get a pointer to any value type, an array of value types, or a string. In the case of arrays and strings, the pointer will actually point to the first element, which is a value type.
Value types declared inline within reference types require the reference type to be pinned, as follows:
class Test
{
int x;
static void Main()
{
Test test = new Test ();
unsafe
{
fixed(int* p = &test.x) // pins test
{
*p = 9;
}
System.Console.WriteLine(test.x);
}
}
}
We describe thefixed statement further in the section “Mapping a Struct to Unmanaged Memory” in Chapter 22.
The Pointer-to-Member Operator
In addition to the & and * operators, C# also provides the C++ style -> operator, which can be used on structs:
struct Test
{
int x;
unsafe static void Main()
{
Test test = new Test();
Test* p = &test;
p->x = 9;
System.Console.WriteLine(test.x);
}
}
Next: Arrays >>
More C# Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|