- 只能用于非托管对象
- 该数组不会检查越界,使用时需要记录数组的大小
- 数组不使用之后需要调用Delete方法释放内存
Last active
March 31, 2024 15:17
-
-
Save Aaron8052/dc85140b751d48c21ac5a89e6c9a244a to your computer and use it in GitHub Desktop.
C#非托管数组
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Runtime.InteropServices; | |
namespace DancingLine.Unsafe | |
{ | |
// this array doesn't have bounds checking, use it with your own risk | |
public unsafe class RawArray<T> where T : unmanaged | |
{ | |
public RawArray(int size) | |
{ | |
Allocate(size); | |
} | |
T* data; | |
void Allocate(int size) | |
{ | |
// alloc heap memory | |
data = (T*)Marshal.AllocHGlobal(size * sizeof(T)); | |
} | |
public T this[int index] | |
{ | |
// return value at index | |
get => *(data + index); | |
// set value at index | |
set => *(data + index) = value; | |
} | |
// dealloc | |
public void Delete() | |
{ | |
if(data == null) | |
return; | |
// free heap memory | |
Marshal.FreeHGlobal((IntPtr)data); | |
data = null; | |
} | |
// destructor: delete heap memory when object is collected by Garbage Collector | |
~RawArray() | |
{ | |
Delete(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment