diff --git a/Core/Extensions/InteropExtensions.cs b/Core/Extensions/InteropExtensions.cs index 2635b623..5c2d39c7 100644 --- a/Core/Extensions/InteropExtensions.cs +++ b/Core/Extensions/InteropExtensions.cs @@ -15,6 +15,44 @@ namespace Vanara.Extensions /// Extension methods for System.Runtime.InteropServices. public static partial class InteropExtensions { +#if ALLOWSPAN + /// Returns the pointer as a . + /// The type of items in the . + /// A pointer to the starting address of a specified number of elements in memory. + /// The number of elements to be included in the . + /// Bytes to skip before starting the span. + /// If known, the total number of bytes allocated to the native memory in . + /// A that represents the memory. + /// + public static unsafe ReadOnlySpan AsReadOnlySpan(this IntPtr ptr, int length, int prefixBytes = 0, SizeT allocatedBytes = default) + { + if (ptr == IntPtr.Zero) return null; + if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); + if (allocatedBytes > 0 && SizeOf() * length + prefixBytes > allocatedBytes) + throw new InsufficientMemoryException(); + + return new ReadOnlySpan((ptr + prefixBytes).ToPointer(), length); + } + + /// Returns the pointer as a . + /// The type of items in the . + /// A pointer to the starting address of a specified number of elements in memory. + /// The number of elements to be included in the . + /// Bytes to skip before starting the span. + /// If known, the total number of bytes allocated to the native memory in . + /// A that represents the memory. + /// + public static unsafe Span AsSpan(this IntPtr ptr, int length, int prefixBytes = 0, SizeT allocatedBytes = default) + { + if (ptr == IntPtr.Zero) return null; + if (length < 0) throw new ArgumentOutOfRangeException(nameof(length)); + if (allocatedBytes > 0 && SizeOf() * length + prefixBytes > allocatedBytes) + throw new InsufficientMemoryException(); + + return new Span((ptr + prefixBytes).ToPointer(), length); + } +#endif + /// Copies the number of specified bytes from one unmanaged memory block to another. /// The allocated memory pointer. /// The allocated memory pointer to copy to.