From 3261fa2ee03bcbf10fb938f2eab676a9251710c6 Mon Sep 17 00:00:00 2001 From: albert-du <52804499+albert-du@users.noreply.github.com> Date: Sun, 13 Mar 2022 09:59:59 -0700 Subject: [PATCH] ReadOnlySpan F# snippets --- .../GetPinnableReference/fs.fsproj | 10 +++++ .../getpinnablereference1.fs | 44 +++++++++++++++++++ xml/System/ReadOnlySpan`1.xml | 1 + 3 files changed, 55 insertions(+) create mode 100644 snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/fs.fsproj create mode 100644 snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.fs diff --git a/snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/fs.fsproj b/snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/fs.fsproj new file mode 100644 index 00000000000..a388306bcba --- /dev/null +++ b/snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/fs.fsproj @@ -0,0 +1,10 @@ + + + Exe + net6.0 + + + + + + \ No newline at end of file diff --git a/snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.fs b/snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.fs new file mode 100644 index 00000000000..eef5a0a473d --- /dev/null +++ b/snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.fs @@ -0,0 +1,44 @@ +#nowarn "9" +#nowarn "51" +open System +open FSharp.NativeInterop + +let createInt32Array () = + [| 100; 200; 300; 400; 500 |] + +[] +let main _ = + let array = createInt32Array() + + // Create a span, pin it, and print its elements. + let span = array.AsSpan() + let spanPtr = &&span.GetPinnableReference() + printfn $"Span contains {span.Length} elements:" + for i = 0 to span.Length - 1 do + printfn $"{NativePtr.get spanPtr i}" + printfn "" + + // Create a read-only span, pin it, and print its elements. + let readonlyspan: ReadOnlySpan = array.AsSpan() + let readonlyspanPtr = &&readonlyspan.GetPinnableReference() + + printfn $"ReadOnlySpan contains {readonlyspan.Length} elements:" + for i = 0 to readonlyspan.Length - 1 do + printfn $"{NativePtr.get readonlyspanPtr i}" + printfn "" + 0 + +// The example displays the following output: +// Span contains 5 elements: +// 100 +// 200 +// 300 +// 400 +// 500 +// +// ReadOnlySpan contains 5 elements: +// 100 +// 200 +// 300 +// 400 +// 500 \ No newline at end of file diff --git a/xml/System/ReadOnlySpan`1.xml b/xml/System/ReadOnlySpan`1.xml index 82300524bd2..4941ccf549d 100644 --- a/xml/System/ReadOnlySpan`1.xml +++ b/xml/System/ReadOnlySpan`1.xml @@ -458,6 +458,7 @@ If pinning a `ReadOnlySpan`, the resulting `char*` __is not__ assumed to b The following example demonstrates creating an integer array, pinning it, and writing each element to the console. :::code language="csharp" source="~/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.cs"::: +:::code language="fsharp" source="~/snippets/fsharp/System/ReadOnlySpanT/GetPinnableReference/getpinnablereference1.fs"::: ]]>