Can't use keyword 'fixed' for a variable in C#
Asked Answered
S

1

5

I tested the keyword fixed with array and string variables and worked really well but I can't use with a single variable.

static void Main() {

    int value = 12345;
    unsafe {
        fixed (int* pValue = &value) { // problem here
            *pValue = 54321;
        }
    }
}

The line fixed (int* pValue = &value) causes a complier error. I don't get it because the variable value is out of the unsafe block and it is not pinned yet.

Why can't I use fixed for the variable value?

Stickpin answered 3/9, 2015 at 20:4 Comment(5)
You should be asking just one question per question, not several. You also haven't included the actual error message for the code in question.Sanmiguel
fixed is used to fix an array not single type.Kropp
@M.kazemAkhgary fixed has two completely orthogonal meanings in different contexts. It's used to create arrays inline in a structure, and it's used to pin a value in memory so that it cannot be moved by the GC while its accessed in unmanaged code.Sanmiguel
Have you tried placing value inside the unsafe block?Guenevere
int value = 12345; is already fixed expression. so you just need its pointer. int* pointer = &value;Kropp
G
16

This is because value is a local variable, allocated on the stack, so it's already fixed. This is mentioned in the error message:

CS0213 You cannot use the fixed statement to take the address of an already fixed expression

If you need the address of value, you don't need the fixed statement, you can get it directly:

int* pValue = &value;
Gruesome answered 3/9, 2015 at 20:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.