vm75 / wasm_ffi

Translates dart:ffi calls on the web to WebAssembly using dart:js
https://github.com/vm75/wasm_ffi
BSD 2-Clause "Simplified" License
7 stars 3 forks source link

wasm_ffi

wasm_ffi intends to be a drop-in replacement for dart:ffi on the web platform using wasm. wasm_ffi is built on top of web_ffi. For ease of use cross-platform, the following are provided:

The general idea is to expose an API that is compatible with dart:ffi but translates all calls through dart:js to a browser running WebAssembly.

Webassembly (wasm) compiled with emscripten as well as standalone wasm is supported.

The provided example shows how to use wasm_ffi both in web and in dart.

Installation

Usage examples

FfiWrapper and ffigen (all platforms)

Direct load example (only for web)

import 'package:wasm_ffi/ffi.dart' as ffi;

Future<void> main() async {
    final library = await DynamicLibrary.open('path to wasm or js'); // NOTE: It is async
    final func = library.lookupFunction<int Function(), int Function()>('functionName');
    print(func());
}

Differences to dart:ffi

While wasm_ffi tries to mimic the dart:ffi API as close as possible, there are some differences. The list below documents the most importent ones, make sure to read it. For more insight, take a look at the API documentation.

Rules for functions (TODO: needs update)

There are some rules and things to notice when working with functions:

Memory (TODO: needs update)

NOTE: While most of this section is still correct, some of it is now automated. The first call you sould do when you want to use wasm_ffi is Memory.init(). It has an optional parameter where you can adjust your pointer size. The argument defaults to 4 to represent 32bit pointers, if you use wasm64, call Memory.init(8). Contraty to dart:ffi where the dart process shares all the memory, on WebAssembly, each instance is bound to a WebAssembly.Memory object. For now, we assume that every WebAssembly module you use has it's own memory. If you think we should change that, open a issue on GitHub and report your usecase. Every pointer you use is bound to a memory object. This memory object is accessible using the @extra Pointer.boundMemory field. If you want to create a Pointer using the Pointer.fromAddress() constructor, you may notice the optional bindTo parameter. Since each pointer must be bound to a memory object, you can explicitly speficy a memory object here. To match the dart:ffi API, the bindTo parameter is optional. Because it is optional, there has to be a fallback mechanism if no bindTo is specified: The static Memory.global field. If that field is also not set, an exception is thrown when invoking the Pointer.fromAddress() constructor. Also, each DynamicLibrary is bound to a memory object, which is again accessible with @extra DynamicLibrary.boundMemory. This might come in handy, since Memory implements the Allocator class.