微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何确保 C# 中非托管对象数组的正确对齐?

如何解决如何确保 C# 中非托管对象数组的正确对齐?

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

基本结构需要如下。

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) 对齐是否足够?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。