我有一个指向整数(未知等级)的多维数组指针传递到我的函数中:
public unsafe static void MyMethod(Array source, ...)
{
//...
}
多维指针数组正在方法之外构造并传入。这是一个例子:
int*[,,,] testArray = new int*[10,10,5,5];
MyMethod(testArray);
如何在数组中的运行时计算索引处设置值? Array.SetValue(...)对于非指针数组非常适用,但拒绝为我的int *数组工作。使用反射器,我看到SetValue减少到调用InternalSetValue,它接受一个值的对象,但它被标记为extern,我看不到实现。我在黑暗中拍了一下,试着用盒装指针传递,但没有运气。
答案 0 :(得分:4)
这有效:
unsafe static void MyMethod(int** array)
{
array[10] = (int*)0xdeadbeef;
}
private static unsafe void Main()
{
int*[, , ,] array = new int*[10, 10, 10, 10];
fixed (int** ptr = array)
{
MyMethod(ptr);
}
int* x = array[0, 0, 1, 0]; // == 0xdeadbeef
}
这有帮助吗?
专家提问:假设数组在内存中连续分配是错误的吗?
答案 1 :(得分:1)
这不起作用,因为无法在.NET中装入指针,因此您永远不能调用Array.SetValue
并传递int*
。
您可以声明MyMethod
接受int*[,,,]
吗?
修改以便进一步阅读,an interesting recent post from Eric Lippert。