动态设置整数指针数组的值

发布于 2024-08-13 17:46:21 字数 473 浏览 1 评论 0原文

我有一个指向整数(未知等级)的多维指针数组被传递到我的函数中,如下所示:

    public unsafe static void MyMethod(Array source, ...)
    {
         //...
    }

多维指针数组正在方法外部构造并传入。这是一个示例:

int*[,,,] testArray = new int*[10,10,5,5];

MyMethod(testArray);

How can I set a value at a数组中运行时计算的索引? Array.SetValue(...) 对于非指针数组工作得很好,但拒绝为我的 int* 数组工作。使用反射器,我看到 SetValue 减少为调用 InternalSetValue,它采用一个对象作为值,但它被标记为 extern,我看不到实现。我在黑暗中尝试了传递盒装指针,但没有成功。

I have a multidimentional array of pointers to integer (of unknown rank) being passed into my function as such:

    public unsafe static void MyMethod(Array source, ...)
    {
         //...
    }

Multidimensional arrays of pointers are being constructed outside of the method and being passed in. Here's an example:

int*[,,,] testArray = new int*[10,10,5,5];

MyMethod(testArray);

How can I set a value at an runtime-computed index in the array? Array.SetValue(...) works perfectly fine for non-pointer arrays, but refuses to work for my int* array. Using reflector, I see SetValue reduces down to calling InternalSetValue which takes an object for the value but it's marked as extern and I can't see the implementation. I took a shot in the dark and tried passing in boxed pointer, but no luck.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

她如夕阳 2024-08-20 17:46:21

这有效:

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
}

这有帮助吗?


请教高手:数组在内存中连续分配的假设是否错误?

This works:

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
}

Does that help?


Question to the experts: Is it wrong to assume that the array is allocated consecutively in memory?

如日中天 2024-08-20 17:46:21

这不起作用,因为不可能在 .NET 中装箱指针,因此您永远无法调用 Array.SetValue 并传递 int*

您可以声明 MyMethod 来接受 int*[,,,] 吗?

编辑:供进一步阅读,Eric Lippert 最近发表的一篇有趣的文章

This doesn't work because it's not possible to box a pointer in .NET, so you can never call the Array.SetValue and pass an int*.

Can you declare MyMethod to accept int*[,,,] instead?

Edit: for further reading, an interesting recent post from Eric Lippert.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文