wasm_ffi 2.3.0
wasm_ffi: ^2.3.0 copied to clipboard
A wrapper for wasm which can be used as a drop-in replacement for dart:ffi for Web platform.
wasm_ffi Example #
This directory contains a complete example of using wasm_ffi to port the opus_dart library to the web.
It demonstrates:
- Compiling a C library (
libopus) to WebAssembly using Emscripten. - Using
ffigenwith a proxy file to generate bindings. - Setting up the necessary boilerplate to initialize
wasm_ffiin a vanilla Dart web app.
Project Structure #
bin/: Contains the main entry point for the vanilla Dart app.lib/src/: Contains the specific binding code (generated.dart), the proxy (proxy_ffi.dart), and initialization logic.web/: Contains the HTML and build artifacts for the web.
Building the C Library #
We use Docker to ensure a consistent build environment for the libopus library.
-
Build the Docker image: The generic
Dockerfileis available in the root of the example. -
Compile to WASM: Detailed instructions and the
Makefileare in theMakefile(if present) or described in the original tutorial. > Note: The pre-compiledlibopus.jsandlibopus.wasmare already included in theweb/directory for convenience.To rebuild them yourself using the Docker method from the original tutorial:
docker build -t wasm_ffi_opus_builder . docker run --rm -v $(pwd):/src wasm_ffi_opus_builder(Adjust the commands based on the actual Dockerfile logic if you want to reproduce the build exactly).
Running the Example #
-
Compile Dart to JavaScript: We use
dart2jsto compile the Dart application code.dart compile js ./bin/main.dart -o ./web/main.dart.js -
Serve the Web Application: You need a simple HTTP server to serve the
webdirectory. We recommenddhttpd.Install
dhttpdif you haven't:dart pub global activate dhttpdRun the server:
cd web dart pub global run dhttpd -p 8080 -
Open in Browser: Navigate to http://localhost:8080 in your browser. Open the Developer Console (F12) to see the output. You should see the Opus version string printed (e.g.,
libopus 1.3.1).
Learn More #
For a detailed explanation of the concepts used here, including how proxy_ffi.dart works and how to support both Native and Web platforms, please refer to the main wasm_ffi README.