diff --git a/Core/Extensions/InteropExtensions.cs b/Core/Extensions/InteropExtensions.cs index 2533275d..d96cf05d 100644 --- a/Core/Extensions/InteropExtensions.cs +++ b/Core/Extensions/InteropExtensions.cs @@ -11,6 +11,26 @@ namespace Vanara.Extensions /// Extension methods for System.Runtime.InteropServices. public static partial class InteropExtensions { + /// + /// Fills the memory with a particular byte value. This is a very dangerous function that can cause memory + /// access errors if the provided is bigger than allocated memory of if the is not a + /// valid memory pointer. + /// + /// The allocated memory pointer. + /// The byte value with which to fill the memory. + /// The number of bytes to fill with the value. + public static void FillMemory(this IntPtr ptr, byte value, int length) + { + if (ptr == IntPtr.Zero || length <= 0) return; + // Write multiples of 8 bytes first + var lval = value == 0 ? 0L : BitConverter.ToInt64(new byte[] { value, value, value, value, value, value, value, value }, 0); + for (var ofs = 0; ofs < length / 8; ofs++) + Marshal.WriteInt64(ptr, ofs * 8, lval); + // Write remaining bytes + for (var ofs = length - (length % 8); ofs < length; ofs++) + Marshal.WriteByte(ptr, length, value); + } + /// /// Gets the length of a null terminated array of pointers. This is a very dangerous function and can result in /// memory access errors if the does not point to a null-terminated array of pointers.