internal static IntPtr GetByteBuffer(this IBuffer buffer) { var byteBuffer = buffer.As <IBufferByteAccess>(); if (byteBuffer == null) { throw new InvalidCastException("Unable to convert WriteableBitmap.PixelBuffer to IBufferByteAccess."); } return(byteBuffer.Buffer); }
} // class WindowsRuntimeBufferUnmanagedMemoryStream private static IntPtr GetPointerAtOffset(this IBuffer buffer, uint offset) { Debug.Assert(0 <= offset); Debug.Assert(offset < buffer.Capacity); unsafe { IntPtr buffPtr = buffer.As <IBufferByteAccess>().Buffer; return(new IntPtr((byte *)buffPtr + offset)); } }
/// <summary> /// Checks if the underlying memory backing two <code>IBuffer</code> instances is actually the same memory. /// When applied to <code>IBuffer</code> instances backed by managed arrays this method is preferable to a naive comparison /// (such as <code>((IBufferByteAccess) buffer).Buffer == ((IBufferByteAccess) otherBuffer).Buffer</code>) because it avoids /// pinning the backing array which would be necessary if a direct memory pointer was obtained. /// </summary> /// <param name="buffer">An <code>IBuffer</code> instance.</param> /// <param name="otherBuffer">An <code>IBuffer</code> instance or <code>null</code>.</param> /// <returns><code>true</code> if the underlying <code>Buffer</code> memory pointer is the same for both specified /// <code>IBuffer</code> instances (i.e. if they are backed by the same memory); <code>false</code> otherwise.</returns> public static bool IsSameData(this IBuffer buffer, IBuffer otherBuffer) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (otherBuffer == null) { return(false); } if (buffer == otherBuffer) { return(true); } byte[] thisDataArr, otherDataArr; int thisDataOffs, otherDataOffs; bool thisIsManaged = buffer.TryGetUnderlyingData(out thisDataArr, out thisDataOffs); bool otherIsManaged = otherBuffer.TryGetUnderlyingData(out otherDataArr, out otherDataOffs); if (thisIsManaged != otherIsManaged) { return(false); } if (thisIsManaged) { return((thisDataArr == otherDataArr) && (thisDataOffs == otherDataOffs)); } IBufferByteAccess thisBuff = buffer.As <IBufferByteAccess>(); IBufferByteAccess otherBuff = otherBuffer.As <IBufferByteAccess>(); unsafe { return(thisBuff.Buffer == otherBuff.Buffer); } }
public static Stream AsStream(this IBuffer source) { if (source == null) { throw new ArgumentNullException(nameof(source)); } byte[] dataArr; int dataOffs; if (source.TryGetUnderlyingData(out dataArr, out dataOffs)) { Debug.Assert(source.Capacity < int.MaxValue); return(new MemoryStream(dataArr, dataOffs, (int)source.Capacity, true)); } unsafe { IBufferByteAccess bufferByteAccess = source.As <IBufferByteAccess>(); return(new WindowsRuntimeBufferUnmanagedMemoryStream(source, (byte *)bufferByteAccess.Buffer)); } }