随着C#7.2中的Memory
,Span
和ArraySegment
的引入,我想知道是否可以将非托管数组表示为可枚举的对象,该对象驻留在堆中。 / p>
后一项要求排除了Span
,该要求基本上实现了我想要的功能:例如
unsafe { bytes = new Span<byte>((byte*)ptr + (index * Width), Width);
是否可以对ArraySegment
或Memory
做同样的事情?他们的构造函数只接受byte[]
,也许有某种方法可以欺骗C#传递byte*
而不是byte[]
?
答案 0 :(得分:9)
对于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>
-仅使用一次-然后使用{{1}代表整个区域的.Slice(...)
上的}。这样,您将拥有一个对象和许多切片(切片是结构,而不是对象)。
请注意,此实现假定您要控制其他地方的内存寿命-这里的.Memory
不会尝试通过Dispose()
释放内存。