我怎样才能快速阅读:在.NET内存映射文件的字节? [英] How can I quickly read bytes from a memory mapped file in .NET?
问题描述
在某些情况下, MemoryMappedViewAccessor
类只是不削减它有效地读取字节;我们得到的最好的是通用的 ReadArray<字节方式>
它所有结构的路线,包括当你只是需要字节数不必要的步骤
In some situations the MemoryMappedViewAccessor
class just doesn't cut it for reading bytes efficiently; the best we get is the generic ReadArray<byte>
which it the route for all structs and involves several unnecessary steps when you just need bytes.
这是可以使用 MemoryMappedViewStream
,但由于它是基于一个流
您需要求到正确的位置,然后再读取操作本身有许多更多不必要的步骤
It's possible to use a MemoryMappedViewStream
, but because it's based on a Stream
you need to seek to the correct position first, and then the read operation itself has many more unnecessary steps.
是否有一个快速,高性能的方式来从读取的字节的阵列内存映射文件在.NET中,因为它应该只是地址空间的特定区域进行读操作?
Is there a quick, high-performance way to read an array of bytes from a memory-mapped file in .NET, given that it should just be a particular area of the address space to read from?
推荐答案
此解决方案要求不安全的代码(编译 /不安全
开关),而是抓住一个指向直接内存;那么 Marshal.Copy
可以使用。这是多少,比由.NET框架提供的方法要快得多。
This solution requires unsafe code (compile with /unsafe
switch), but grabs a pointer to the memory directly; then Marshal.Copy
can be used. This is much, much faster than the methods provided by the .NET framework.
// assumes part of a class where _view is a MemoryMappedViewAccessor object
public unsafe byte[] ReadBytes(int offset, int num)
{
byte[] arr = new byte[num];
byte *ptr = (byte*)0;
this._view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
Marshal.Copy(IntPtr.Add(new IntPtr(ptr), offset), arr, 0, num);
this._view.SafeMemoryMappedViewHandle.ReleasePointer();
return arr;
}
public unsafe void WriteBytes(int offset, byte[] data)
{
byte* ptr = (byte*)0;
this._view.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
Marshal.Copy(data, 0, IntPtr.Add(new IntPtr(ptr), offset), data.Length);
this._view.SafeMemoryMappedViewHandle.ReleasePointer();
}
这篇关于我怎样才能快速阅读:在.NET内存映射文件的字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!