1

一直在阅读这是一个“不安全”的代码,而“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;
}
4

1 回答 1

2

如果要在 C# 中使用指针运算,则需要使用 unsafe 和fixed 关键字,如下所示:

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;
        }
    }
}
于 2012-06-20T10:23:43.643 回答