12

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];
            ...
        }
    }

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I think factory pattern is definitely the way to go here.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.