About Unsafe Code

There are cases in which you can't use managed code. For instance, many native Win32 functions require pointers. One of the problems C/C++ programmers often had with Visual Basic was the lack of pointers. Visual Basic .NET still doesn't support pointers, but it does support a similar mechanism called a reference type. Still, in some cases, pointers can come in handy. You might also need to access unmanaged legacy code. In the best of all worlds, all our programs would magically be converted to managed code because of the advantages it offers, but sometimes this isn't possible. So what about the times when you really need a pointer or need to access legacy code? For these situations, C# provides a special keyword: unsafe. A method or a section of code can be declared as unsafe, and when compiled using the /unsafe compiler switch, will generate unsafe (unmanaged) code that isn't verifiable by the runtime. In addition to unsafe, C# provides the fixed keyword. During the process of garbage collection, variables are often moved to make more efficient use of memory. If several smaller blocks of free memory are required for a single, larger allocation, the garbage collector can move the blocks to make the single larger block available. Such rearranging would obviously be disastrous for any program that had stored, within unsafe code, a pointer to one of the variables the garbage collector moved. The fixed keyword was added for just this situation. Within a fixed block, the variables referenced will be pinned and won't be movable. After exiting the fixed block, the variables are once again available for the garbage collector to move as required.

Was this article helpful?

0 0

Post a comment