2011-09-27 21 views
6

Ben derleme değil bu kodu vardır: Ben neden kod derlemek olmayacağını biliyorum[] uint için uint * dönüştürülemez

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

Şimdi ama noktada anlaşılan değilim Düşünmek için çok yorgunum ve beni doğru yönde koymak için biraz yardıma ihtiyacım var. Bir süredir güvensiz bir kodla çalışmadım, ama eminim ki bir Array.Copy (veya Buffer.BlockCopy?) Yapmalı ve dizinin bir kopyasını vermem gerekiyor, ancak ihtiyaç duyduğum argümanları almıyorlar. Ne hakkında unutuyorum?

Teşekkürler. Bir fixed tampon ile çalışırken

cevap

4

Bir fixed bağlamda çalışmak zorunda:

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! Utanç verici bir şekilde basit bir şey olacağını biliyordum. Teşekkürler! –

2

daha kolay bir çözüm olabilir, ancak bu çalışır: Bu int ile çalışır

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

, float Yalnızca byte, char ve double, ancak verileri sabit diziden yönetilen diziye taşımak için Marshal.Copy() kullanabilirsiniz.

Örnek:

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); 
      } 
     } 
    } 
} 
İlgili konular