views:

483

answers:

3

Afternoon all,

a little help if you please. In order to circumvent the 2Gb object limit in .NET I have made a class that allocates memory on the heap and this allows me to create arrays up to the limit of my free RAM. However, for ease of development (as it was a proof of concept) it was hard coded for longs. Now that it works I've been trying to alter the code to use generics so I can use the same code for multiple types.

In allocating the memory and correctly index the array I need an array of pointers of the same type that the array will hold i.e. a long array needs long*[] myLargeArray. The problem is when I use generics this declaration becomes T*[] myLargeArray, which always produces the error 'Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')'

Thanks in advance.

PS Before anyone asks, yes I really do need such large arrays.

Code example for a 2D array:


    LargeArray <int> myArray = new LargeArray<int>(x, y);

    public unsafe class LargeArray where T : struct
    {
        ...
        private T*[] tArr;
        ...
        public LargeArray(long sizeI, long sizeJ)
        {
            ...
            myLargeArray = new T*[sizeI];
            ...
        }
    }

A: 

From MSDN

Even when used with the unsafe keyword, taking the address of a managed object, getting the size of a managed object, or declaring a pointer to a managed type is not allowed. For more information, see Unsafe Code and Pointers (C# Programming Guide).

Also I don't know if you are, but make sure you're using fixed keyword in your code.

Stan R.
+4  A: 

According to the C# programming guide:

Any of the following types may be a pointer type:

  • sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool
  • Any enum type.
  • Any pointer type.
  • Any user-defined struct type that contains fields of unmanaged types only.

When you place the struct constraint on your generic type, the compiler does not have enough information to infer that all of the above requirements will be met (specifically the last point).

Since we don't have templates in C#, you may want to consider creating overloads of your array/pointer adapter for the numeric types that make sense, or a factory class that creates a LargeArray given a size of a certain type.

Steve Guidi
I think factory pattern is definitely the way to go here.
Tamás Szelei
A: 

Thanks for the replies, and apologies for my delay in replying.

I take it from your replies that there is no way to restrict the generic type constraint to be just the numerical types, say for instance just short, int and long? I imagine this would mean having to find an interface that is unique to the types I wished to allow within those allowed by the struct constraint.

I'll look into the overloading of the array/pointer adapter and factory classes, thanks for the suggestions.

Brendan