diff --git a/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs new file mode 100644 index 00000000..842ba39c --- /dev/null +++ b/src/ComputeSharp.Graphics/Buffers/Extensions/GraphicsResourceExtensions.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections; +using System.Diagnostics.Contracts; +using System.Linq; +using System.Reflection; +using ComputeSharp.Graphics.Buffers.Abstract; + +namespace ComputeSharp.Graphics.Buffers.Extensions +{ + /// + /// A with extension methods for the type to allocate generic resources + /// + internal static class GraphicsResourceExtensions + { + /// + /// Allocates a new constant buffer with the specified generic value + /// + /// The instance to use to allocate the buffer + /// The input to copy to the allocated buffer + /// A constant instance (as a ) with the input data + [Pure] + public static GraphicsResource AllocateReadOnlyBufferFromReflectedSingleValue(this GraphicsDevice device, object data) + { + // Create the generic constant buffer + Type + dataType = data.GetType(), + bufferType = typeof(ReadOnlyBuffer<>).MakeGenericType(dataType); + ConstructorInfo constructor = bufferType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).First(); + GraphicsResource buffer = (GraphicsResource)constructor.Invoke(new object[] { device, 1 }); + + // Create the array with the input value + Type arrayType = dataType.MakeArrayType(); + ConstructorInfo[] arrayConstructors = arrayType.GetConstructors(BindingFlags.CreateInstance + | BindingFlags.Public + | BindingFlags.Instance + | BindingFlags.OptionalParamBinding); + Array array = (Array)arrayConstructors[0].Invoke(new object[] { 1 }); + + // Use the IList indexer to set the generic object + IList ilist = array; + ilist[0] = data; + + // Set the input data to the new buffer + MethodInfo setDataMethod = bufferType.GetMethod(nameof(HlslBuffer.SetData), new[] { arrayType }); + setDataMethod.Invoke(buffer, new object[] { array }); + + return buffer; + } + } +}