Search code examples
javascript.netwebassemblyjsimportbrowser-wasm

What is a MemoryView in the .NET browser-wasm runtime?


In the new (non-Blazor) browser-wasm runtime of .NET 7 there are JSImport attributes for communicating with Javascript imports. Many .NET types are supported for passing as arguments to Javascript functions.

If you pass a Span<> or ArraySegment<> then you must marshal them as a MemoryView, but I can't see any documentation for what that actually is. What does the JS function actually receive? Is it a wrapper for a typed array?


Solution

  • While not documented, we can see the implementation of MemoryView here: https://github.com/dotnet/runtime/blob/8cb3bf89e4b28b66bf3b4e2957fd015bf925a787/src/mono/wasm/runtime/marshal.ts#L379

    It has the functions

    • byteLength
    • copyTo
    • length
    • set
    • slice
    • _unsafe_create_view

    set and slice behave like the TypedArray functions (in particular, slice makes a new buffer.) _unsafe_create_view looks like an internal function, but it is exposed, and would let you get the TypedArray directly, which would be slightly more efficient.