Browse Source

export example

221V 7 months ago
parent
commit
45cc631ae6
3 changed files with 65 additions and 0 deletions
  1. 23 0
      README.md
  2. 11 0
      add_two.d
  3. 31 0
      index.html

+ 23 - 0
README.md

@@ -1,2 +1,25 @@
 # D + WASM, example
 
+```
+$ vim ~/.bashrc
+export PATH=$PATH:~/.dlang/bin
+
+$ source ~/.bashrc
+
+$ ldc2 -v
+binary    /home/e/.dlang/bin/ldc2
+version   1.39.0 (DMD v2.109.1, LLVM 18.1.6)
+config    /home/e/.dlang/etc/ldc2.conf (x86_64-unknown-linux-gnu)
+
+
+ldc2 -mtriple=wasm32-unknown-unknown-wasm -O --betterC add_two.d
+
+
+$ ls -alh add_two.wasm
+$ ~/git/wabt/build/wasm-decompile add_two.wasm -o add_two.txt
+
+
+$ python3 -m http.server
+// http://0.0.0.0:8000/
+```
+

+ 11 - 0
add_two.d

@@ -0,0 +1,11 @@
+
+extern(C): // disable D mangling
+
+int add_two(int a, int b){
+  return a + b;
+}
+
+void _start(){  } // seems to be the required entry point
+
+// https://wiki.dlang.org/Generating_WebAssembly_with_LDC
+

+ 31 - 0
index.html

@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>WASM Demo</title>
+</head>
+<body>
+  <div id="result"></div>
+
+
+<script>
+var div = document.getElementById('result');
+
+function test1(ex){
+  div.innerText = 'add_two(1, 2) = ' + ex.add_two(1, 2);
+}
+
+window.addEventListener("load", function(){
+  var env = { env: {} };
+  WebAssembly.instantiateStreaming( fetch('add_two.wasm'), env).then( result => {
+    console.log('WASM loaded!');
+    var ex = result.instance.exports;
+    console.log('ex = ', ex);
+    test1(ex);
+  });
+  
+}, false);
+</script>
+
+</body>
+</html>
+