I'm implementing an unmanaged array class in C# which I need for some OpenGL calls.
It's going great, but I've hit a roadblock. The following code doesn't compile, and I understand why, but how can I make it work?
public T this[int i]
{
get { return *((T*)arrayPtr + i); }
set { *((T*)arrayPtr + i) = value; }
}
I thought that it might work if I ensured that T is a struct
unsafe class FixedArray<T> where T : struct
Doesn't work either...
How can I get something functionally equivilant to what I'm trying to do above?
EDIT: I'm using an unmanaged array with Marshal.AllocHGlobal() so that my array is fixed and the GC won't move it around. OpenGL doesn't actually process the instructions when you call it, OpenGL will try to access the array long after the function has returned.
Here's the whole class if that helps:
unsafe class FixedArray<T> where T : struct
{
IntPtr arrayPtr;
public T this[int i]
{
get { return *((T*)arrayPtr + i); }
set { *((T*)arrayPtr + i) = value; }
}
public FixedArray(int length)
{
arrayPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(T)) * length);
}
~FixedArray()
{
Marshal.FreeHGlobal(arrayPtr);
}
}
The error message is Cannot take the address of, get the size of, or declare a pointer to a managed type ('T')
arrayPtr
from your call toAllocHGlobal
– Gawky