2011-09-27 18 views
6

tengo este código que no se compila:no puede convertir uint * a uint []

public struct MyStruct 
{ 
    private fixed uint myUints[32]; 
    public uint[] MyUints 
    { 
     get 
     { 
      return this.myUints; 
     } 
     set 
     { 
      this.myUints = value; 
     } 
    } 
} 

Ahora, sé qué el código no se compilará, pero estoy al parecer, en el punto donde estoy demasiado cansado para pensar y necesito ayuda para ponerme en la dirección correcta. No he trabajado con el código inseguro en un tiempo, pero estoy bastante seguro de que necesito hacer un Array.Copy (o Buffer.BlockCopy?) Y devolver una copia de la matriz, sin embargo, esos no toman los argumentos que necesito. ¿De qué me olvido?

Gracias.

Respuesta

4

usted tiene que trabajar en un contexto fixed cuando se trabaja con un buffer fixed:

public unsafe struct MyStruct { 
    private fixed uint myUints[32]; 
    public uint[] MyUints { 
     get { 
      uint[] array = new uint[32]; 
      fixed (uint* p = myUints) { 
       for (int i = 0; i < 32; i++) { 
        array[i] = p[i]; 
       } 
      } 
      return array; 
     } 
     set { 
      fixed (uint* p = myUints) { 
       for (int i = 0; i < 32; i++) { 
        p[i] = value[i]; 
       } 
      } 
     } 
    } 
} 
+0

Ah! Sabía que iba a ser algo embarazosamente simple. ¡Gracias! –

2

Puede haber una solución más fácil, pero esto funciona:

public unsafe struct MyStruct 
{ 
    private fixed uint myUints[32]; 
    public uint[] MyUints 
    { 
     get 
     { 
      fixed (uint* ptr = myUints) 
      { 
       uint[] result = new uint[32]; 
       for (int i = 0; i < result.Length; i++) 
        result[i] = ptr[i]; 
       return result; 
      } 
     } 
     set 
     { 
      // TODO: make sure value's length is 32 
      fixed (uint* ptr = myUints) 
      { 
       for (int i = 0; i < value.Length; i++) 
        ptr[i] = value[i]; 
      } 
     } 
    } 
} 
0

Esto funciona con int, float , byte, char y double solamente, pero puede usar Marshal.Copy() para mover datos de la matriz fija a la matriz administrada.

Ejemplo:

class Program 
{ 
    static void Main(string[] args) 
    { 
     MyStruct s = new MyStruct(); 

     s.MyUints = new int[] { 
      1, 2, 3, 4, 5, 6, 7, 8, 
      9, 10, 11, 12, 13, 14, 15, 16, 
      1, 2, 3, 4, 5, 6, 7, 8, 
      9, 10, 11, 12, 13, 14, 15, 16 }; 

     int[] chk = s.MyUints; 
     // chk containts the proper values 
    } 
} 

public unsafe struct MyStruct 
{ 
    public const int Count = 32; //array size const 
    fixed int myUints[Count]; 

    public int[] MyUints 
    { 
     get 
     { 
      int[] res = new int[Count]; 
      fixed (int* ptr = myUints) 
      { 
       Marshal.Copy(new IntPtr(ptr), res, 0, Count); 
      } 
      return res; 
     } 
     set 
     { 
      fixed (int* ptr = myUints) 
      { 
       Marshal.Copy(value, 0, new IntPtr(ptr), Count); 
      } 
     } 
    } 
} 
Cuestiones relacionadas