How to ensure the correct alignment of an array of unmanaged objects in C#?

90 Views Asked by At

I need to create an object that manages the lifetime of an unmanaged array.

The basic structure needs to be as follows.

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; }
}

The bit that I am unsure about is what else I need to add in order to ensure that the alignment of the objects in the array are as it should be? Is it sufficient to align objects to sizeof(T)?

0

There are 0 best solutions below