开发者

C#: Using a generic to create a pointer array

开发者 https://www.devze.com 2022-12-10 01:58 出处:网络
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 lim

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 reall开发者_StackOverflow社区y 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];
            ...
        }
    }


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消