我正在C#中實現一個非託管數組類,我需要一些OpenGL調用。在C中實現一個通用的非託管數組#
這很好,但我遇到了障礙。下面的代碼不能編譯,我明白爲什麼,但我怎麼才能使它工作?
public T this[int i]
{
get { return *((T*)arrayPtr + i); }
set { *((T*)arrayPtr + i) = value; }
}
我認爲可能的工作,如果我保證T是一個結構
unsafe class FixedArray<T> where T : struct
不工作,要麼...
我怎樣才能得到的東西功能equivilant什麼,我上面想要做什麼?
編輯:我正在使用與Marshal.AllocHGlobal()的非託管數組,以便我的數組是固定的,GC不會移動它。 OpenGL在調用它時並不實際處理指令,OpenGL將在函數返回後嘗試訪問數組。
這裏是全班同學是否有幫助:
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);
}
}
該錯誤消息無法獲取地址,得到的大小,或宣佈一個指向託管類型(「T」)
請包含錯誤消息。 – Richard 2011-03-22 08:03:00
你確定你需要一個非託管數組嗎? – Gabe 2011-03-22 08:06:07
是的,我確定。我第一次嘗試它沒有得到AccessViolationExceptions。 – Hannesh 2011-03-22 08:12:08