Search code examples
c++-cli

Create Managed Array with long/size_t length


Jumping straight to code, this is what I would like to do:

size_t len = obj->someLengthFunctionThatReturnsTypeSizeT();
array<int>^ a = gcnew array<int>(len);

When I try this, I get the error

conversion from size_t to int, possible loss of data

Is there a way I can get this code to compile without explicitly casting to int? I find it odd that I can't initialize an array to this size, especially because there is a LongLength property (and how could you get a length as a long - bigger than int - if you can only initialize a length as an int?).

Thanks!

P.S.: I did find this article that says that it may be impractical to allocate an array that is truly size_t, but I don't think that is a concern. The point is that the length I would like to initialize to is stored in a size_t variable.


Solution

  • Managed arrays are implemented for using Int32 as indices, there is no way around that. You cannot allocate arrays larger than Int32.MaxValue.

    You could use the static method Array::CreateInstance (the overload that takes a Type and an array of Int64), and then cast the resulting System::Array to the appropriate actual array type (e.g. array<int>^). Note that the passed values must not be larger than Int32.MaxValue. And you would still need to cast.

    So you have at least two options. Either casting:

    // Would truncate the value if it is too large
    array<int>^ a = gcnew array<int>((int)len);
    

    or this (no need to cast len, but the result of CreateInstance):

    // Throws an ArgumentOutOfRangeException if len is too large
    array<int>^ a = (array<int>^)Array::CreateInstance(int::typeid, len);  
    

    Personally, i find the first better. You still might want to check the actual size of len so that you don't run into any of the mentioned errors.