Beispiel #1
0
        /// <summary>
        /// Function to write a generic value to the stream.
        /// </summary>
        /// <typeparam name="T">Type of value to write.  Must be a value type.</typeparam>
        /// <param name="value">Value to write to the stream.</param>
        /// <exception cref="System.IO.IOException">Thrown when the stream is read-only.</exception>
        public unsafe void Write <T>(T value)
            where T : struct
        {
            ValidateAccess(true);

            int   size    = DirectAccess.SizeOf <T>();
            byte *pointer = stackalloc byte[size];

            DirectAccess.WriteValue(pointer, ref value);

            while (size > 0)
            {
                if (size >= 8)
                {
                    Writer.Write(*((long *)pointer));
                    pointer += 8;
                    size    -= 8;
                }
                else if (size >= 4)
                {
                    Writer.Write(*((int *)pointer));
                    pointer += 4;
                    size    -= 4;
                }
                else if (size >= 2)
                {
                    Writer.Write(*((short *)pointer));
                    pointer += 2;
                    size    -= 2;
                }
                else
                {
                    Writer.Write(*pointer);
                    pointer++;
                    size--;
                }
            }
        }
 /// <summary>
 /// Function to write a specific value type to the memory pointed at by the pointer.
 /// </summary>
 /// <typeparam name="T">Type of value to write.</typeparam>
 /// <param name="destination">The destination pointer.</param>
 /// <param name="value">The value to write.</param>
 /// <remarks>This method can only write value types composed of primitives, reference objects will not work.
 /// <para>There is no way to determine the size of the data pointed at by the pointer, so the user must take care not to write outside the bounds of the memory.</para>
 /// </remarks>
 public static void Write <T>(this IntPtr destination, ref T value)
     where T : struct
 {
     DirectAccess.WriteValue(destination, ref value);
 }