Main Site Documentation

Unsafe code


#1

All sources state that unsafe code is not allowed on NETMF.

public static unsafe long DoubleToInt64Bits(double value)
        {
            return *(((long*)&value));
        }

Tick the “Allow unsafe code” in project properties and it works!
Further on I found out that actually the “fixed” keyword isn’t supported, pointers do work.

So I want to ask how dangerous is it to use code like the above, does the GC kick in after a method has finished, does it pause execution after A line of code or after an IL opcode.
Finally is this an undocumented feature/bug that will be different on other devices or even removed.


#2

Edit: According to what I heard from the experts, using unsafe is not an option and can lead to a very-difficult-to-fix problems.


#3

Would you mind shedding some light on exactly what goes wrong?


#4

Garbage collector can kick in randomly and move objects that you are trying to access.


#5

What if they are all on the stack? Would that be problematic.

EDIT: I’m just asking cuz I had a talk with some C# experts, and they all said as long as they are on the stack its okay because the GC doesn’t touch the stack.


#6

And how did these expert say you can pit objects on stack? :slight_smile:

Anyway, unsafe is not supported


#7

Local ValueTypes are on the stack, which is what the parameter and int variable are in the code I sent you.


#8

oh yes your are right. I was thinking references on stack…many users confuse the reference with the actually object.