Skip to content

Instantly share code, notes, and snippets.

@Aaron8052
Last active March 31, 2024 15:17
Show Gist options
  • Save Aaron8052/dc85140b751d48c21ac5a89e6c9a244a to your computer and use it in GitHub Desktop.
Save Aaron8052/dc85140b751d48c21ac5a89e6c9a244a to your computer and use it in GitHub Desktop.
C#非托管数组

C#非托管数组

注意

  • 只能用于非托管对象
  • 该数组不会检查越界,使用时需要记录数组的大小
  • 数组不使用之后需要调用Delete方法释放内存
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