Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the implications of using unsafe code

Tags:

Aside from the fact that the code itself can access memory directly. What are the other implications of using the "/unsafe" compiler flag and the "fixed" keyword? Are there any knock on effects related to code signing and deployment of my .exe (my app is desktop only)?

(This isn't about whether or not I should be doing this, the why is covered in my question here)

like image 795
Matt Warren Avatar asked Apr 01 '09 17:04

Matt Warren


People also ask

What does it mean for code to be unsafe?

What Does Unsafe Mean? Unsafe is a C programming language (C#) keyword used to denote a section of code that is not managed by the Common Language Runtime (CLR) of the . NET Framework, or unmanaged code.

Why do we use unsafe in C#?

Unsafe code in C# isn't necessarily dangerous; it's just code whose safety cannot be verified. Unsafe code has the following properties: Methods, types, and code blocks can be defined as unsafe. In some cases, unsafe code may increase an application's performance by removing array bounds checks.

Should I use unsafe in Rust?

If we implement a type that contains a type that is not Send or Sync , such as raw pointers, and we want to mark that type as Send or Sync , we must use unsafe .

Is Unsafe code faster?

Unsafe code typically runs faster than a corresponding safe implementation, which in this case would have required a nested loop with array indexing and bounds checking.


1 Answers

You can put the implications into two buckets.

The first is how it affects your application environment. Using unsafe code requires that your assembly be run in a full trust environment. It's not possible to run in a restricted environment such as certain Click Once security settings. The reason being that unsafe code prevents the CLR from ensuring type safety. Click Once though with no security restrictions should not have a problem.

The second is what it means for the way you code. Using unsafe code typically involves using pointers and in particular, using them to performed advanced marshalling via PInvoke. There is nothing inherently wrong with either of these actions though. It just requires significantly more understanding of the CLR and marshalling than "safe" code does. Object pinning is a great example of knowledge you'd need to have a firm grasp on before you started using these features.

like image 134
JaredPar Avatar answered Nov 03 '22 14:11

JaredPar