0

The code in question (below) reads much faster (30x), tahn regular: MemoryMappedViewAccessor.ReadArray() I'm trying to modify the code to be able to read from long offset, not int (!)

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

original code is here: How can I quickly read bytes from a memory mapped file in .NET?_

I need to adjust IntPtr.Add and Marshal.Copy to correctly work with long offset Thank you in advance!

  • You don't need to have a `long` offset. You can chunk your long value into integers and iterate over those values. – Eldar Nov 23 '22 at 20:57
  • Dear Eldar! Thank you for a prompt reply - As I see Marshal.Copy copies a pointer to specific location - I see no way to iterate as int-s - please explain your idea! – Yurii Palkovskii Nov 23 '22 at 21:02
  • With the help of this [asnwer](https://stackoverflow.com/a/6219932/12354911). Let's assume your offset is now two integer values so your final pointer will be sth like this :`var finalPtr =IntPtr.Add(IntPtr.Add(new IntPtr(ptr), offsets[0]),offsets[1])` – Eldar Nov 23 '22 at 21:15

2 Answers2

1

new IntPtr(intPtr.ToInt64() + longOffset)

Of course, this works in 64 bit processes only.

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36
0

Thank you, Klaus Gütter! Complete working code, based on your suggested method:

public static unsafe byte[] ReadBytes(long l_offset, int i_read_buf_size, MemoryMappedViewAccessor mmva)
    {
        byte[] arr = new byte[i_read_buf_size];
        byte* ptr = (byte*)0;
        mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
        IntPtr p = new(ptr);
        Marshal.Copy(new IntPtr(p.ToInt64() + l_offset), arr, 0, i_read_buf_size);
        mmva.SafeMemoryMappedViewHandle.ReleasePointer();
        return arr;
    }