Browse Source

export example

221V 1 year ago
parent
commit
68c5201953
3 changed files with 60 additions and 0 deletions
  1. 22 0
      README.md
  2. 7 0
      add_two.zig
  3. 31 0
      index.html

+ 22 - 0
README.md

@@ -1,3 +1,25 @@
 # ZIWA = Zig + WASM, example
 
+```
+$ zig version
+0.13.0
+
+ -O Debug
+ -O ReleaseSafe
+ -O ReleaseSmall
+ -O ReleaseFast
+
+$ zig build-exe add_two.zig -target wasm32-freestanding -fno-entry --export=add_two
+$ zig build-exe add_two.zig -O ReleaseFast -target wasm32-freestanding -fno-entry --export=add_two
+
+
+$ 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/
+
+```
+
 

+ 7 - 0
add_two.zig

@@ -0,0 +1,7 @@
+
+//pub fn add_two(a: i32, b: i32) i32 {
+export fn add_two(a: i32, b: i32) i32 {
+  return a + b;
+}
+
+

+ 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>
+