Skip to content

Instantly share code, notes, and snippets.

@sachaarbonel
Forked from graphicbeacon/index.html
Created June 4, 2019 22:23
Show Gist options
  • Save sachaarbonel/eec96fe025540f49d0fa87b88578ef47 to your computer and use it in GitHub Desktop.
Save sachaarbonel/eec96fe025540f49d0fa87b88578ef47 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment