Pointers and Arrays in C# - Arrays
(Page 3 of 4 )
The stackalloc keyword
Memory can be allocated in a block on the stack explicitly using the stackalloc keyword. Since it is allocated on the stack, its lifetime is limited to the execution of the method, just as with any other local variable. The block may use the [] operator to index into memory.
int* a = stackalloc int [10];
for (int i = 0; i < 10; ++i)
onsole.WriteLine(a[i]); // print raw memory
Fixed-size buffers
Memory can be allocated in a block within a struct using the fixed keyword:
fixed keyword:Memory can be allocated in a block within a struct using the fixed keyword:
unsafe struct UnsafeUnicodeString
{
public short Length;
public fixed byte Buffer[30];
}
unsafe class UnsafeClass
{
private UnsafeUnicodeString uus;
public UnsafeClass (string s)
{
uus.Length = (short)s.Length;
fixed (byte* p = uus.Buffer)
for (int i = 0; i < s.Length; i++)
p[i] = (byte)s[i];
}
}
class Test
{
static void Main() {new UnsafeClass("Christian Troy");}
}
Thefixedkeyword is also used in this example to pin the object on the heap that contains the buffer (which will be the instance ofUnsafeClass).
void*
Rather than pointing to a specific value type, a pointer may make no assumptions about the type of the underlying data. This approach is useful for functions that deal with raw memory. An implicit conversion exists from any pointer type to void*. A void* cannot be dereferenced, and arithmetic operations cannot be performed on void pointers. For example:
class Test
{
unsafe static void Main ()
{
short[ ] a = {1,1,2,3,5,8,13,21,34,55};
fixed (short* p = a)
{
//sizeof returns size of value-type in bytes
Zap (p, a.Length * sizeof (short));
}
foreach (short x in a)
System.Console.WriteLine (x); // prints all zeros
}
unsafe static void Zap (void* memory, int byteCount)
{
byte* b = (byte*)memory;
for (int i = 0; i < byteCount; i++)
*b++ = 0;
}
}
Pointers to Unmanaged Code
Pointers are also useful for accessing data outside the managed heap (such as when interacting with C DLLs or COM), or when dealing with data not in the main memory (such as graphics memory or a storage medium on an embedded device).
Next: Preprocessor Directives >>
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.
|
|