The type of a local declared in a fixed statement must be a pointer type

I'm trying to fix the bellow code compiler giving error: The type of a local declared in a fixed statement must be a pointer type.

anyone can tell me what's wrong here

       sbyte[] array = (sbyte[])(Array)Encoding.Default.GetBytes("MyAESCtr"); ;

        fixed (sbyte[] array4 = array)
            sbyte* algo;
            if (array != null && array4.Length != 0)
                algo = &array4[0];
                algo = null;

here is the function I send values to :

 public unsafe int Encrypt(sbyte* Algo, sbyte* szd, sbyte* ped)
 internal unsafe static extern int EncryptC(sbyte*, sbyte*, _UString*, sbyte*);

1 answer

  • answered 2020-03-31 10:11 Marc Gravell

    When using fixed like this, the new variable is the pointer, i.e.

    fixed (sbyte* array4 = array)

    However! I don't think you need unsafe code here, and you probably shouldn't be pinning here. Just... use it as an array! There needs to be a very good reason to use fixed/unsafe, and I just don't see any reason here. If you just want the value:

    var algo = array[0];

    If you really need a pointer, prefer a managed pointer:

    ref sbyte algo = ref array[0];

    edit; from comments, it seems that there is some P/Invoke going on here; that is a valid scenario for fixed, in which case this should work fine:

    fixed (sbyte* ptr = array)
        sbyte* algo = null;
        if (array != null && array.Length != 0)
            algo = ptr; // &ptr[0] **is** ptr

    Important: you must not use the pointer once you've left the fixed scope; the pointer is unreliable after that point due to how the GC works.