1

我需要创建一个对象来管理非托管数组的生命周期。

基本结构需要如下。

using System;
using System.Runtime.InteropServices;

internal sealed class UnmanagedArray<T>
    where T : unmanaged
{
    private readonly nint resource;

    public UnmanagedArray(nint length)
    {
        if (length < 0)
        {
            throw new ArgumentException("Array size must be non-negative.");
        }

        unsafe
        {
            // allocate an extra object so that it can be used to store a sentinel value.
            this.resource = Marshal.AllocHGlobal(sizeof(T) * (length + 1));
            this.Begin = (T*)this.resource;
            this.End = this.Begin + length;
            this.Length = length;
        }
    }

    ~UnmanagedArray()
    {
        Marshal.FreeHGlobal(this.resource);
    }

    public unsafe T* Begin { get; }

    public unsafe T* End { get; }

    public nint Length { get; }
}

我不确定的一点是我还需要添加什么以确保数组中对象的对齐方式是应该的?对齐对象是否足够sizeof(T)

4

0 回答 0