【问题标题】:Array.Copy --> Arrays larger than 2GB are not supportedArray.Copy --> 不支持大于 2GB 的数组
【发布时间】:2017-12-15 13:35:36
【问题描述】:

我正在使用Array.Copy Method (Array, Array, Int64)。我有以下静态方法

public static T[,] Copy<T>(T[,] a)
    where T : new()
{
    long n1 = a.GetLongLength(0);
    long n2 = a.GetLongLength(1);
    T[,] b = new T[n1, n2];
    System.Array.Copy(a, b, n1 * n2);
    return b;
}

和下面的代码来测试它

double[,] m1 = new double[46340, 46340];
double[,] m2 = Copy(m1); // works

double[,] m3 = new double[46341, 46341];
double[,] m4 = Copy(m3); // Arrays larger than 2GB are not supported
                         // length argument of Array.Copy

我知道 &lt;gcAllowVeryLargeObjects enabled="true" /&gt; 并且我已将其设置为 true。

我在Array.Copy Method (Array, Array, Int64)的文档中看到,长度参数有以下注释。

一个 64 位整数,表示要复制的元素数。整数必须介于零和Int32.MaxValue 之间(含)。

我不明白为什么当类型为Int64 时长度参数有这个限制?有解决方法吗?是否计划在即将发布的 .net 版本中取消此限制?

【问题讨论】:

    标签: c# arrays multidimensional-array .net-4.5 gcallowverylargeobjects


    【解决方案1】:

    解决方法可能是以下代码

    public static T[,] Copy<T>(T[,] a)
        where T : new()
    {
        long n1 = a.GetLongLength(0);
        long n2 = a.GetLongLength(1);
        long offset = 0;
        long length = n1 * n2;
        long maxlength = Int32.MaxValue;
        T[,] b = new T[n1, n2];
        while (length > maxlength)
        {
            System.Array.Copy(a, offset, b, offset, maxlength);
            offset += maxlength;
            length -= maxlength;
        }
        System.Array.Copy(a, offset, b, offset, length);
        return b;
    }
    

    数组被复制到大小为Int32.MaxValue的块中。

    【讨论】:

    • @AdamHouldsworth 我已经用 double(大小为 8)进行了测试,即使一个数组块约为 16 GB,它看起来也能正常工作。
    • @AdamHouldsworth 但 OP 使用的是gcAllowVeryLargeObjects,因此没有 2 GB 的限制。
    • @wollmich 哦,抱歉,我明白了,数组大小没有问题,只是在当前的Copy 实现中似乎存在人为的限制。
    • @AdamHouldsworth 我现在也尝试使用Guid[,] m1 = new Guid[46341, 46341]Guid[,] m2 = Copy(m1)。这似乎也有效。所以异常消息Arrays larger than 2GB are not supported 也不对。
    • 数组对元素的数量有限制。 The source seems to protect this。即使启用了大对象,我也无法分配byte[] b = new byte[int.MaxValue - 1]。多维数组在运行时被认为是一个数组还是多个数组?这可能掩盖了每个对象的存储限制,但我认为数组元素计数限制仍然存在。貌似Copy 不能处理多维数组?
    猜你喜欢
    • 1970-01-01
    • 2016-04-15
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 2011-11-08
    相关资源
    最近更新 更多