2012-06-20 34 views
1

已經讀過這是一個「不安全」的代碼,「IntPtr」通常不是以這種方式運行。無法將索引用[]應用於類型爲'System.IntPtr'的表達式

有人可以提出一個替代方案或解決方案。

我的技能在C#中有限。謝謝你的幫助 !!

for (num4 = 1; num4 < i; num4 += 2) 
{ 
    for (num = num4; num <= length; num += num5) 
    { 
     num2 = num + i; 
     num11 = (num7 * numRef[(num2 - 1) * 8]) - (num8 * numRef[num2 * 8]); 
     double num10 = (num7 * numRef[num2 * 8]) + (num8 * numRef[(num2 - 1) * 8]); 
     numRef[(num2 - 1) * 8] = numRef[(num - 1) * 8] - num11; 
     numRef[num2 * 8] = numRef[num * 8] - num10; 
     IntPtr ptr1 = (IntPtr)(numRef + ((num - 1) * 8)); 
     //ptr1[0] += (IntPtr) num11; 
     ptr1[0] += (IntPtr)num11; 
     IntPtr ptr2 = (IntPtr)(numRef + (num * 8)); 
     //ptr2[0] += (IntPtr) num10; 
     ptr2[0] += (IntPtr)num10; 
    } 

    num7 = (((num9 = num7) * num13) - (num8 * num14)) + num7; 
    num8 = ((num8 * num13) + (num9 * num14)) + num8; 
} 
+0

你到底是想用這個代碼來完成什麼? –

+0

你從哪裏得到這段代碼?如果你是C#的新手,使用不安全的代碼通常不是明智之舉,因爲它不安全。 – BoltClock

+1

@BoltClock - 我認爲這段代碼直接來自地獄本身... – Polity

回答

2

如果你想使用C#指針運算,你將需要使用不安全和fixed keyword,具體如下:

public unsafe void Foo() 
{ 
    int[] managedArray = new int[100000]; 

    // Pin the pointer on the managed heap 
    fixed (int * numRef = managedArray) 
    { 
     for (num4 = 1; num4 < i; num4 += 2) 
     { 
      for (num = num4; num <= length; num += num5) 
      { 
       num2 = num + i; 
       num11 = (num7 * numRef[(num2 - 1) * 8]) - (num8 * numRef[num2 * 8]); 
       double num10 = (num7 * numRef[num2 * 8]) + (num8 * numRef[(num2 - 1) * 8]); 

       // You can now index the pointer 
       // and use pointer arithmetic 
       numRef[(num2 - 1) * 8] = numRef[(num - 1) * 8] - num11; 
       numRef[num2 * 8] = numRef[num * 8] - num10; 
       ... 
       int * offsetPtr = numRef + 100; 

       // Equivalent to setting numRef[105] = 5; 
       offsetPtr[i+5] = 5; 
      } 

      num7 = (((num9 = num7) * num13) - (num8 * num14)) + num7; 
      num8 = ((num8 * num13) + (num9 * num14)) + num8; 
     } 
    } 
} 
相關問題