Skip to content

Instantly share code, notes, and snippets.

@graphicbeacon
Last active May 20, 2020 14:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save graphicbeacon/a2ed9b6e39a7391a893e8fe7dac25fa0 to your computer and use it in GitHub Desktop.
Save graphicbeacon/a2ed9b6e39a7391a893e8fe7dac25fa0 to your computer and use it in GitHub Desktop.
WebAssembly in Dart for web example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="scaffolded-by" content="https://github.com/google/stagehand" />
<title>webassembly_example</title>
<link rel="stylesheet" href="styles.css" />
<link rel="icon" href="favicon.ico" />
<script defer src="main.dart.js"></script>
</head>
<body></body>
</html>
// web/main.dart
import 'dart:html';
import 'package:js/js_util.dart';
import './wa_interop.dart';
void main() async {
var request = await HttpRequest.request(
'./simple.wasm',
responseType: 'arraybuffer',
mimeType: 'application/wasm',
);
var wa = await instantiate(
request.response,
jsObj({
'imports': {
'imported_func': (args) => window.console.log(args),
})
});
wa.then((results) {
window.console.log(results);
var exportsObj = getProperty(results.instance, 'exports');
Function exportedFn = getProperty(exportsObj, 'exported_func');
exportedFn();
});
}
;; web/simple.wasm
(module
(type $t0 (func (param i32)))
(type $t1 (func))
(import "imports" "imported_func" (func $imports.imported_func (type $t0)))
(func $exported_func (type $t1)
i32.const 42
call $imports.imported_func)
(export "exported_func" (func $exported_func)))
// web/wa_interop.dart
@JS('WebAssembly')
library wasm_interop;
import 'dart:html';
import 'package:js/js.dart';
import 'package:js/js_util.dart';
@JS()
external instantiate(bytes, dynamic importObj);
jsObj(Map<String, dynamic> dartMap) {
var jsObject = newObject();
dartMap.forEach((name, value) {
if (value is Map<String, dynamic>) {
setProperty(jsObject, name, jsObj(value));
} else {
setProperty(jsObject, name, value);
}
});
return jsObject;
}
@graphicbeacon
Copy link
Author

This uses the js package for interop with WebAssembly's instantiate() method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment