2011-09-27 2 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?)을 수행하고 배열 사본을 반환해야한다고 확신하지만 필자는 필요한 인수를 취하지 않습니다. 나는 무엇에 관해 잊고 있냐?

감사합니다. fixed 버퍼로 작업 할 때

답변

4

당신은 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

쉬운 해결책이있을 수 있지만,이 작품 : 이것은 int 작동

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

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