Ejemplo n.º 1
0
        /// <summary>
        /// Writes the contents of an array to the buffer. More efficient with
        /// large arrays.
        /// </summary>
        /// <typeparam name="T">The type of element to write.</typeparam>
        /// <param name="array">The values to write.</param>
        public unsafe void Write <T>(T[] array) where T : unmanaged
        {
            var length = UnsafeUtils.LengthInBytes(array);

            if (length > 0)
            {
                var handle = GCHandle.Alloc(array, GCHandleType.Pinned);

                try
                {
                    // ensure there is enough space for the new content
                    if (BytesRemaining < length)
                    {
                        GrowBuffer(length);
                    }

                    // start from where we last finished writting
                    var src = handle.AddrOfPinnedObject();

                    // copy the memory using an optimal method
                    Buffer.MemoryCopy(src.ToPointer(), m_ptr.ToPointer(), BytesRemaining, length);
                    m_ptr += length;
                }
                finally
                {
                    // always free the handle, even if an exception occurs
                    handle.Free();
                }
            }
        }