unsafe static void SquarePtrParam (int* p)
{
*p *= *p;
}
VS
static void SquarePtrParam (ref int p)
{
p *= p;
}
C# supports an unsafe context, in which you may write unverifiable code. In an unsafe context, code may use pointers, allocate and free blocks of memory, and call methods using function pointers. Unsafe code in C# isn't necessarily dangerous; it's just code whose safety cannot be verified.
In general, the code that we write in C# is safe code. It creates managed objects and doesn't access the memory directly. On the other hand, unsafe code in C# is code that is not in direct control of the Common Language Runtime (CLR).
In an unsafe programming language, errors are not trapped. Rather, after executing an erroneous operation the program keeps going, but in a silently faulty way that may have observable consequences later on.
All the code we've discussed so far has had Rust's memory safety guarantees enforced at compile time. However, Rust has a second language hidden inside it that doesn't enforce these memory safety guarantees: it's called unsafe Rust and works just like regular Rust, but gives us extra superpowers.
Safe code can run in any situation where you can run C# code (Silverlight, shared hosting ASP.NET, XNA, SQL Server, etc.), while unsafe code require elevated trust. This means you can run your code in more places and with fewer restrictions.
Also, it's safe, meaning you don't have to worry about doing something wrong and crashing your process.
Your example is not a good one, the JIT compiler already generates the code like that. Under the hood references are pointers too. This needed to be fast, managed code would never have been competitive.
The garbage collected heap is pretty incompatible with pointers, you have to pin objects to make it possible to create a pointer to them. Without the pinning, the garbage collector could move the object and your code randomly fails, destroying the heap integrity. Pinning has a non-zero cost, both in the operation and the loss of efficiency you'll suffer, well after you unpinned, when a garbage collection happens while an object is pinned.
Pointers are highly effective when accessing unmanaged memory. The canonical example is image processing that requires accessing the pixels of a bitmap. And it is a way to quickly access pinned arrays with all the safety interlocks removed, array index checking isn't free when you don't iterate them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With