Status: not possible yet (#126). This document records what was tried
with matrix-rust-sdk matrix-sdk-ffi/20260909, uniffi-bindgen-cs 0.11.0 and .NET 10.0.12 (wasm-tools workload), what
works and what blocks it, so the work can be picked up once the blockers are resolved upstream.
.NET on browser-wasm (Blazor WebAssembly, wasmbrowser, wasmconsole) can't load shared libraries, native code has
to be statically linked into dotnet.native.wasm with emscripten. The bindings keep working unchanged through
[DllImport], so the plan is:
- Build
matrix-sdk-ffias a static library forwasm32-unknown-emscriptenwith the emscripten version of the .NET workload (3.1.56 for .NET 10). - Link it into the app with
<NativeFileReference>and<WasmBuildNative>true</WasmBuildNative>.
matrix-sdk-fficompiles forwasm32-unknown-emscriptenwith three small SDK patches (see below) and links into a .NET 10 wasm app.- A P/Invoke into the library (
ffi_matrix_sdk_ffi_uniffi_contract_version) runs in the .NET wasm runtime under Node. - The uniffi API on wasm differs from the native one only by the SQLite parts (24 symbols:
SqliteStoreBuilder,ClientBuilder.SqliteStore,ClientBuilder.SessionPaths, secrets bundle database functions and their checksums). matrix-sdk-ffi additionally exposesClientBuilder.IndexeddbStoreon wasm.
On every target_family = "wasm" target matrix-rust-sdk uses wasm-bindgen: wasm-bindgen is a non-optional dependency
of matrix-sdk-common, tasks are spawned with wasm_bindgen_futures::spawn_local, reqwest uses its fetch backend, the
only usable store is IndexedDB (SQLite needs tokio/fs, which tokio doesn't support on wasm) and timers use
gloo-timers.
The JavaScript side of these imports is generated by the wasm-bindgen CLI, which only supports
wasm32-unknown-unknown. Linked with the full bindings, dotnet.native.wasm imports 195 functions from the
__wbindgen_placeholder__ module (IndexedDB, fetch, setTimeout, queueMicrotask, promises, ...) and fails to
instantiate:
WebAssembly.instantiate(): Import #3 module="__wbindgen_placeholder__" error: module is not an object or function
wasm-bindgen gained experimental emscripten support
(Cloudflare, 2026-09), but it is pre-release and relies on
emscripten's -sWASM_BINDGEN setting, which emscripten 3.1.56 of the .NET 10 workload doesn't have.
The generated bindings register every callback interface and the future continuation callback with
Marshal.GetFunctionPointerForDelegate (165 calls, 189 delegate types) in the static constructor of _UniFFILib. Mono on wasm only
supports native-to-managed calls into [UnmanagedCallersOnly] (or [MonoPInvokeCallback]) methods, so the first call into
the bindings fails, even synchronous ones like SdkGitSha():
System.PlatformNotSupportedException: No native to managed transition for method
'void Matrix.RustSdk.Bindings.UniffiCallbackInterfaceAccountDataListener:OnChange (...)', missing [UnmanagedCallersOnly] attribute.
This needs a change in the uniffi-bindgen-cs templates. Full AOT on iOS fails for the same reason: NordSecurity/uniffi-bindgen-cs#175.
These are solved or have known workarounds, but would have to go into the build once the blockers are gone.
-
matrix-sdk-ffi doesn't compile for wasm. matrix-rust-sdk's CI checks the core crates on wasm but not
matrix-sdk-ffi, which always enablesmatrix-sdk/experimental-search. The search code boxes its streams asSend, which doesn't hold on wasm. Patch (fits upstream, it affectswasm32-unknown-unknowntoo):--- a/crates/matrix-sdk/src/message_search.rs +++ b/crates/matrix-sdk/src/message_search.rs +#[cfg(not(target_family = "wasm"))] type RoomResultStream = Pin<Box<dyn Stream<Item = Result<(f32, OwnedEventId), IndexError>> + Send>>; +#[cfg(target_family = "wasm")] +type RoomResultStream = Pin<Box<dyn Stream<Item = Result<(f32, OwnedEventId), IndexError>>>>; --- a/crates/matrix-sdk-ui/src/search_service.rs +++ b/crates/matrix-sdk-ui/src/search_service.rs +#[cfg(not(target_family = "wasm"))] type ResultsStream = Pin<Box<dyn Stream<Item = Result<Vec<(OwnedRoomId, TimelineEvent)>, SearchError>> + Send>>; +#[cfg(target_family = "wasm")] +type ResultsStream = + Pin<Box<dyn Stream<Item = Result<Vec<(OwnedRoomId, TimelineEvent)>, SearchError>>>>; --- a/bindings/matrix-sdk-ffi/src/search_service.rs +++ b/bindings/matrix-sdk-ffi/src/search_service.rs - self.inner.set_query(query).await.map_err(|err| ClientError::from(anyhow::Error::from(err))) + self.inner.set_query(query).await.map_err(ClientError::from_err) - self.inner.paginate().await.map_err(|err| ClientError::from(anyhow::Error::from(err))) + self.inner.paginate().await.map_err(ClientError::from_err)
-
gloo-timers doesn't compile with
panic=unwind(the emscripten default): wasm-bindgen requiresUnwindSafeclosures then. Build withRUSTFLAGS="-C panic=abort". -
No SQLite: build with
--no-default-features --features js,indexeddb,unstable-msc4274,experimental-element-recent-emojis,experimental-push-secrets,experimental-search. The C# bindings would need a wasm variant without the SQLite API (or stubs), otherwise the checksum check fails. -
Only the static library:
cargo buildalso links thecdylibas an emscripten side module, which fails (zstd-sysisn't built with-fPIC). Usecargo rustc --crate-type staticlib. -
Library name: the P/Invoke table uses the file name of the
NativeFileReference, so the archive has to be calledmatrix_sdk_ffi.a(notlibmatrix_sdk_ffi.a) to match[DllImport("matrix_sdk_ffi")]. -
Newer LLVM than emscripten 3.1.56: the SDK needs Rust 1.95+, whose objects declare the wasm features
bulk-memory-optandcall-indirect-overlong. emcc passes them to its binaryen, which doesn't know them (Unknown option '--enable-bulk-memory-opt'). Stripping thetarget_featuressection isn't enough because emcc then disables bulk memory. It worked with awasm-optwrapper that drops the two flags; a proper fix would rewrite the feature names in the objects'target_featuressections. -
WasmNativeStrip: the .NET DWARF strip step runswasm-optwith onlysimd,exception-handlingandbulk-memoryenabled, but Rust's default wasm features also includenontrapping-fptoint,sign-ext,reference-typesandmultivalue. Set<WasmNativeStrip>false</WasmNativeStrip>. -
Size: the debug build of
dotnet.native.wasmis 134 MB, a release build withopt-level = "z"and LTO is needed.
Build the static library in the emscripten image matching the .NET workload, on a copy of the submodule with the patch applied:
docker run --rm -v "$PWD/matrix-rust-sdk:/sdk" -w /sdk emscripten/emsdk:3.1.56 bash -c '
curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --target wasm32-unknown-emscripten
. $HOME/.cargo/env
RUSTFLAGS="-C panic=abort" cargo rustc --locked -p matrix-sdk-ffi --lib --crate-type staticlib \
--target wasm32-unknown-emscripten --no-default-features \
--features js,indexeddb,unstable-msc4274,experimental-element-recent-emojis,experimental-push-secrets,experimental-search
cp target/wasm32-unknown-emscripten/debug/libmatrix_sdk_ffi.a matrix_sdk_ffi.a'Then link it into a .NET app (mcr.microsoft.com/dotnet/sdk:10.0 with dotnet workload install wasm-tools and
python3), with the wasm-opt wrapper from above:
<Project Sdk="Microsoft.NET.Sdk.WebAssembly">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<WasmBuildNative>true</WasmBuildNative>
<WasmNativeStrip>false</WasmNativeStrip>
<WasmMainJSPath>main.mjs</WasmMainJSPath>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../src/Matrix.RustSdk.Bindings/Matrix.RustSdk.Bindings.csproj" />
<NativeFileReference Include="matrix_sdk_ffi.a" />
</ItemGroup>
</Project>dotnet publish -c Release and run node main.mjs in bin/Release/net10.0/publish/wwwroot (with a package.json
containing {"type": "module"}).
- Separate wasm module: build
matrix-sdk-ffiforwasm32-unknown-unknownwith wasm-bindgen (the configuration matrix-rust-sdk supports, used by uniffi-bindgen-react-native for the web) and call it from C# through[JSImport]/[JSExport]instead of P/Invoke. Both modules have separate memories, so everyRustBufferhas to be copied and callbacks go through JavaScript. That needs a different bindings generator, uniffi-bindgen-cs can't produce it. - Wait for upstream: once wasm-bindgen's emscripten support is released and .NET ships an emscripten with
-sWASM_BINDGEN, and uniffi-bindgen-cs generates[UnmanagedCallersOnly]callbacks, the static linking approach above should work with the listed workarounds.