Skip to content

5. F# support ✈️

Sergio Pedri edited this page Aug 1, 2022 · 2 revisions

If you're wondering whether it is possible to use ComputeSharp from an F# project, it is!

There is a caveat though: since the HLSL shader rewriter specifically works on C# syntax, it is necessary to write the actual shaders in C#. A simple way to do this is to have a small C# project with just the shader types, and then reference it from an F# project that will contain all the actual logic: every API to create GPU devices, allocate buffers and invoke shaders will work perfectly fine from F# as well.

Assuming we had the MultiplyByTwo shader defined in the Getting started 📖 paragraph referenced from a C# project, here is how we can actually use it directly from our F# project, with the same sample described above:

let array = [| for i in 1 .. 100 -> (float32)i |]

// Create the graphics buffer
use buffer = GraphicsDevice.GetDefault().AllocateReadWriteBuffer(array)

let shader = new MultiplyByTwo(buffer)

// Run the shader (passed by reference)
GraphicsDevice.Default.For(100, &shader)

// Get the data back
buffer.CopyTo array

For a complete example, check out the F# sample here.

Clone this wiki locally