Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

graphicbeacon commented Apr 27, 2019

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
You can’t perform that action at this time.