gpt4 book ai didi

C# 使用 Memory 或 ArraySegment 访问非托管数组?

转载 作者:太空狗 更新时间:2023-10-29 20:04:09 27 4
gpt4 key购买 nike

随着 C# 7.2 中 MemorySpanArraySegment 的引入,我想知道是否可以将非托管数组表示为可枚举数组对象,存在于堆中。

后一个要求排除了 Span,它基本上实现了我想要的:例如

unsafe { bytes = new Span<byte>((byte*)ptr + (index * Width), Width); 

是否可以对 ArraySegmentMemory 做同样的事情?他们的构造函数只接受 byte[],也许有一些方法可以欺骗 C# 传递 byte* 而不是 byte[]

最佳答案

Memory<T> , 但您需要创建自己的 MemoryManager<T> .别担心 - 这并不像听起来那么可怕 - here's one I wrote earlier... :

/// <summary>
/// A MemoryManager over a raw pointer
/// </summary>
/// <remarks>The pointer is assumed to be fully unmanaged, or externally pinned - no attempt will be made to pin this data</remarks>
public sealed unsafe class UnmanagedMemoryManager<T> : MemoryManager<T>
where T : unmanaged
{
private readonly T* _pointer;
private readonly int _length;

/// <summary>
/// Create a new UnmanagedMemoryManager instance at the given pointer and size
/// </summary>
/// <remarks>It is assumed that the span provided is already unmanaged or externally pinned</remarks>
public UnmanagedMemoryManager(Span<T> span)
{
fixed (T* ptr = &MemoryMarshal.GetReference(span))
{
_pointer = ptr;
_length = span.Length;
}
}
/// <summary>
/// Create a new UnmanagedMemoryManager instance at the given pointer and size
/// </summary>
public UnmanagedMemoryManager(T* pointer, int length)
{
if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
_pointer = pointer;
_length = length;
}
/// <summary>
/// Obtains a span that represents the region
/// </summary>
public override Span<T> GetSpan() => new Span<T>(_pointer, _length);

/// <summary>
/// Provides access to a pointer that represents the data (note: no actual pin occurs)
/// </summary>
public override MemoryHandle Pin(int elementIndex = 0)
{
if (elementIndex < 0 || elementIndex >= _length)
throw new ArgumentOutOfRangeException(nameof(elementIndex));
return new MemoryHandle(_pointer + elementIndex);
}
/// <summary>
/// Has no effect
/// </summary>
public override void Unpin() { }

/// <summary>
/// Releases all resources associated with this object
/// </summary>
protected override void Dispose(bool disposing) { }
}

现在您可以使用:

var mgr = new UnmanagedMemoryManager((byte*)ptr + (index * Width), Width);
Memory<byte> memory = mgr.Memory;

memory可以存储在堆上。

但是,为了尽量减少分配,您可能希望创建一个单个 UnmanagedMemoryManager<byte>覆盖整个区域 - 仅一次 - 然后使用 .Slice(...).Memory 上代表整个地区。这样你就有了一个对象和很多切片(切片是结构,而不是对象)。

请注意,此实现假设您要控制其他地方的内存生命周期 - Dispose()这里试图通过Marshal释放内存等

关于C# 使用 Memory<T> 或 ArraySegment<T> 访问非托管数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52190423/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com