// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.InteropServices; using SharpDX.Direct3D; namespace SharpDX { /// /// Provides methods to perform fast read/write random access data on a buffer located in an unmanaged memory. /// /// /// This class doesn't validate the position read/write from. It is the responsibility of the client of this class /// to verify that access is done within the size of the buffer. /// public class DataBuffer : DisposeBase { private unsafe sbyte* _buffer; private GCHandle _gCHandle; private readonly bool _ownsBuffer; private readonly int _size; #if !WINDOWS_UWP private Blob _blob; #endif /// /// Creates the specified user buffer. /// /// Type of the buffer. /// The buffer to use as a DataBuffer. /// Index inside the buffer in terms of element count (not size in bytes). /// True to keep the managed buffer and pin it, false will allocate unmanaged memory and make a copy of it. Default is true. /// An instance of a DataBuffer public static DataBuffer Create(T[] userBuffer, int index = 0, bool pinBuffer = true) where T : struct { unsafe { if (userBuffer == null) throw new ArgumentNullException("userBuffer"); if (index < 0 || index > userBuffer.Length) throw new ArgumentException("Index is out of range [0, userBuffer.Length-1]", "index"); DataBuffer buffer; var sizeOfBuffer = Utilities.SizeOf(userBuffer); var indexOffset = index * Utilities.SizeOf(); if (pinBuffer) { var handle = GCHandle.Alloc(userBuffer, GCHandleType.Pinned); buffer = new DataBuffer(indexOffset + (byte*)handle.AddrOfPinnedObject(), sizeOfBuffer - indexOffset, handle); } else { // The .NET Native compiler crashes if '(IntPtr)' is removed. buffer = new DataBuffer(indexOffset + (byte *)(IntPtr)Interop.Fixed(userBuffer), sizeOfBuffer - indexOffset, true); } return buffer; } } /// /// Initializes a new instance of the class, and allocates a new buffer to use as a backing store. /// /// The size of the buffer to be allocated, in bytes. /// /// is less than 1. public DataBuffer(int sizeInBytes) { unsafe { System.Diagnostics.Debug.Assert(sizeInBytes > 0); _buffer = (sbyte*)Utilities.AllocateMemory(sizeInBytes); _size = sizeInBytes; _ownsBuffer = true; } } /// /// Initializes a new instance of the class. /// /// The data pointer. public DataBuffer(DataPointer dataPointer) : this(dataPointer.Pointer, dataPointer.Size) { } /// /// Initializes a new instance of the class, using an unmanaged buffer as a backing store. /// /// A pointer to the buffer to be used as a backing store. /// The size of the buffer provided, in bytes. public unsafe DataBuffer(IntPtr userBuffer, int sizeInBytes) : this((void*)userBuffer, sizeInBytes, false) { } internal unsafe DataBuffer(void* buffer, int sizeInBytes, GCHandle handle) { System.Diagnostics.Debug.Assert(sizeInBytes > 0); _buffer = (sbyte*)buffer; _size = sizeInBytes; _gCHandle = handle; _ownsBuffer = false; } internal unsafe DataBuffer(void* buffer, int sizeInBytes, bool makeCopy) { System.Diagnostics.Debug.Assert(sizeInBytes > 0); if (makeCopy) { _buffer = (sbyte*)Utilities.AllocateMemory(sizeInBytes); Utilities.CopyMemory((IntPtr)_buffer, (IntPtr)buffer, sizeInBytes); } else { _buffer = (sbyte*)buffer; } _size = sizeInBytes; _ownsBuffer = makeCopy; } #if !WINDOWS_UWP internal unsafe DataBuffer(Blob buffer) { System.Diagnostics.Debug.Assert(buffer.GetBufferSize() > 0); _buffer = (sbyte*)buffer.GetBufferPointer(); _size = buffer.GetBufferSize(); _blob = buffer; } #endif /// /// Releases unmanaged and - optionally - managed resources /// /// true to release both managed and unmanaged resources; false to release only unmanaged resources. protected override void Dispose(bool disposing) { if (disposing) { #if !WINDOWS_UWP if (_blob != null) { _blob.Dispose(); _blob = null; } #endif } if (_gCHandle.IsAllocated) _gCHandle.Free(); unsafe { if (_ownsBuffer && _buffer != (sbyte*)0) { Utilities.FreeMemory((IntPtr)_buffer); _buffer = (sbyte*)0; } } } /// /// Clears the buffer. /// public unsafe void Clear(byte value = 0) { Utilities.ClearMemory((IntPtr)_buffer, value, Size); } /// /// Gets a single value from the current buffer at the specified position. /// /// Relative position in bytes from the beginning of the buffer to get the data from. /// The type of the value to be read from the buffer. /// The value that was read. public T Get(int positionInBytes) where T : struct { unsafe { T result = default(T); Utilities.Read((IntPtr)(_buffer + positionInBytes), ref result); return result; } } /// /// Gets a single value from the current buffer at the specified position. /// /// The type of the value to be read from the buffer. /// Relative position in bytes from the beginning of the buffer to get the data from. /// The value as out. /// The value that was read. public void Get(int positionInBytes, out T value) where T : struct { unsafe { Utilities.ReadOut((IntPtr)(_buffer + positionInBytes), out value); } } /// /// Gets an array of values from a position in the buffer. /// /// Relative position in bytes from the beginning of the buffer to get the data from. /// number of T instance to get from the positionInBytes /// The type of the values to be read from the buffer. /// An array of values that was read from the current buffer. public T[] GetRange(int positionInBytes, int count) where T : struct { unsafe { var result = new T[count]; Utilities.Read((IntPtr)(_buffer + positionInBytes), result, 0, count); return result; } } /// /// Gets a sequence of elements from a position in the buffer into a target buffer. /// /// Relative position in bytes from the beginning of the buffer to get the data from. /// An array of values to be read from the buffer. /// The zero-based byte offset in buffer at which to begin storing /// the data read from the current buffer. /// The number of values to be read from the current buffer. public void GetRange(int positionInBytes, T[] buffer, int offset, int count) where T : struct { unsafe { Utilities.Read((IntPtr) (_buffer + positionInBytes), buffer, offset, count); } } /// /// Sets a single value to the buffer at a specified position. /// /// The type of the value to be written to the buffer. /// Relative position in bytes from the beginning of the buffer to set the data to. /// The value to write to the buffer. public void Set(int positionInBytes, ref T value) where T : struct { unsafe { Interop.CopyInline(_buffer + positionInBytes, ref value); } } /// /// Sets a single value to the buffer at a specified position. /// /// The type of the value to be written to the buffer. /// Relative position in bytes from the beginning of the buffer to set the data to. /// The value to write to the buffer. public void Set(int positionInBytes, T value) where T : struct { unsafe { Interop.CopyInline(_buffer + positionInBytes, ref value); } } /// /// Sets the specified value. /// /// Relative position in bytes from the beginning of the buffer to set the data to. /// The value. public void Set(int positionInBytes, bool value) { unsafe { *((int*)(_buffer + positionInBytes)) = value?1:0; } } /// /// Sets an array of values to a specified position into the buffer. /// /// Relative position in bytes from the beginning of the buffer to set the data to. /// An array of values to be written to the current buffer. public void Set(int positionInBytes, T[] data) where T : struct { Set(positionInBytes, data, 0, data.Length); } /// /// Sets a range of data to a specified position into the buffer. /// /// Relative position in bytes from the beginning of the buffer to set the data to. /// A pointer to the location to start copying from. /// The number of bytes to copy from source to the current buffer. public void Set(int positionInBytes, IntPtr source, long count) { unsafe { Utilities.CopyMemory((IntPtr)(_buffer + positionInBytes), source, (int)count); } } /// /// Sets an array of values to a specified position into the buffer. /// /// The type of the values to be written to the buffer. /// Relative position in bytes from the beginning of the buffer to set the data to. /// An array of values to be written to the buffer. /// The zero-based offset in data at which to begin copying values to the current buffer. /// The number of values to be written to the current buffer. If this is zero, /// all of the contents will be written. public void Set(int positionInBytes, T[] data, int offset, int count) where T : struct { unsafe { Utilities.Write((IntPtr)(_buffer + positionInBytes), data, offset, count); } } /// /// Gets a pointer to the buffer used as a backing store.. /// /// An IntPtr to the buffer being used as a backing store. public IntPtr DataPointer { get { unsafe { return new IntPtr(_buffer); } } } /// /// Gets the length in bytes of the buffer. /// /// A long value representing the length of the buffer in bytes. public int Size { get { return _size; } } /// /// Performs an explicit conversion from to . /// /// The from value. /// The result of the conversion. public static implicit operator DataPointer(DataBuffer from) { return new DataPointer(from.DataPointer, (int)from.Size); } } }