From a8ef6e11c8b6b022695f8261fe2895a7750a4f20 Mon Sep 17 00:00:00 2001 From: dahall Date: Thu, 10 Sep 2020 10:13:56 -0600 Subject: [PATCH] Added NativeMemoryStream.ReadToPtr and WriteFromPtr methods to interact with allocated memory. --- Core/InteropServices/NativeMemoryStream.cs | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/Core/InteropServices/NativeMemoryStream.cs b/Core/InteropServices/NativeMemoryStream.cs index d5b73db3..ee704607 100644 --- a/Core/InteropServices/NativeMemoryStream.cs +++ b/Core/InteropServices/NativeMemoryStream.cs @@ -279,6 +279,24 @@ namespace Vanara.InteropServices return p != IntPtr.Zero ? (T?)(T)p.Convert((uint)Capacity - (uint)Position, typeof(T), CharSet.Auto) : null; } + /// Copies a specified number of bytes from the stream to a memory location. + /// + /// The pointer to the memory location that will recieve the bytes. The caller must ensure that sufficient memory has been allocated + /// to this pointer. + /// + /// The number of bytes to read. + public void ReadToPtr(IntPtr ptr, long bytesToRead) + { + if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); + if (bytesToRead < 0) throw new ArgumentOutOfRangeException(nameof(bytesToRead)); + ThrowIfDisposed(); + if (!CanRead) throw new NotSupportedException(); + if (bytesToRead == 0) return; + if (Position + bytesToRead > Capacity) throw new ArgumentOutOfRangeException(nameof(bytesToRead)); + PositionPtr.CopyTo(ptr, bytesToRead); + Position = position + bytesToRead; + } + /// Sets the position within the current stream. /// A byte offset relative to the parameter. /// @@ -390,6 +408,24 @@ namespace Vanara.InteropServices } } + /// Writes bytes from a memory location into the stream. + /// + /// The pointer to the memory location from which to retrieve the bytes to write. The caller must ensure that this memory location + /// has at least of allocated memory. + /// + /// The number of bytes to write from . + public void WriteFromPtr(IntPtr ptr, long bytesToWrite) + { + if (ptr == IntPtr.Zero) throw new ArgumentNullException(nameof(ptr)); + if (bytesToWrite < 0) throw new ArgumentOutOfRangeException(nameof(bytesToWrite)); + ThrowIfDisposed(); + if (access == FileAccess.Read) throw new NotSupportedException(); + EnsureCapacity(Position + bytesToWrite); + ptr.CopyTo(PositionPtr, bytesToWrite); + position += bytesToWrite; + length += bytesToWrite; + } + /// Writes the specified value into the stream. This function should fail if the object cannot be blitted. /// The value to write. public virtual void WriteObject(object value)