Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsafe method to get pointer to byte array

is this behaviour will be valid in C#

public class MyClass
{
    private byte[] data;
    public MyClass()
    {
        this.data = new byte[1024];
    }
    public unsafe byte* getData()
    {
        byte* result = null;
        fixed (byte* dataPtr = data)
        {
            result = dataPtr;
        }
        return result;
    }
}
like image 472
uray Avatar asked Nov 28 '22 07:11

uray


1 Answers

If you are going to turn off the safety system then you are responsible for ensuring the memory safety of the program. As soon as you do, you are required to do everything safely without the safety system helping you. That's what "unsafe" means.

As the C# specification clearly says:

the address of a moveable variable can only be obtained using a fixed statement, and that address remains valid only for the duration of that fixed statement.

You are obtaining the address of a moveable variable and then using it after the duration of the fixed statement, so the address is no longer valid. You are therefore specifically required to not do precisely what you are doing.

You should not write any unsafe code until you have a thorough and deep understanding of what the rules you must follow are. Start by reading all of chapter 18 of the specification.

like image 61
Eric Lippert Avatar answered Dec 06 '22 17:12

Eric Lippert