2011-09-27 107 views
6

我有這樣的代碼不編譯:不能轉換UINT *爲uint []

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

現在,我知道爲什麼代碼將無法編譯,但是我在點很明顯我太累了想不到,需要一些幫助才能讓我走向正確的方向。我有一段時間沒有使用不安全的代碼,但我很確定我需要做一個Array.Copy(或Buffer.BlockCopy?)並返回數組的副本,但是那些不需要我需要的參數。我忘了什麼?

謝謝。

回答

4

你有一個fixed方面的工作與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

啊!我知道這會是一件令人尷尬的事情。謝謝! –

2

有可能是一個更簡單的解決方案,但這個工程:

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

這適用於intfloatbyte,chardouble,但您可以使用Marshal.Copy()將數據從固定陣列移到託管陣列。

例子:

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); 
      } 
     } 
    } 
}